使用C#数据集读取xml文件

本文关键字:xml 文件 读取 数据集 使用 | 更新日期: 2024-06-14 03:24:26

我有一个xml文件,其中包含以下数据:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Tables xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <countries>
        <country country_id = "1" name = "Afghanistan"/>
        <country country_id = "2" name = "Albania"/>
        <country country_id = "3" name = "Algeria"/>
    </countries>
</Tables>

当我尝试使用下面的C#代码时,

DataSet ds_XMLData= new DataSet();
ds_XMLData.ReadXml(XMLFile);

我有两张桌子:具有一列countries_id和一行值为"0"的countriescountry,包含3列-其他列为countries_id,所有行的值为"0"

你能帮我理解为什么数据集中没有一个只有两列(country_id和name)的国家/地区表吗?

此外,为什么在所有表中都添加了额外的列countries_id。

注意:-我希望继续使用基于属性的xml文件格式。

使用C#数据集读取xml文件

简单地说,您可以使用XmlReader来完成。ReadToFollowing方法:

xmlFile.ReadToFollowing("countries");
DataSet ds_XMLData= new DataSet();
ds_XMLData.ReadXml(XMLFile);

只需去掉<countries />元素。例如,

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Tables xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <country country_id = "1" name = "Afghanistan"/>
   <country country_id = "2" name = "Albania"/>
   <country country_id = "3" name = "Algeria"/>
</Tables>

我不是DataSet专家,但我猜这是在试图创建一种从countriescountry的关系,而这是你不想要的。如果可以控制XML,只需修改XML即可。

我不知道DataSet为什么要创建两个表和额外的列。但我认为,在从XML加载数据之前,必须先阅读XML模式。

DataSet dataSet = new DataSet();
dataSet.ReadXmlSchema("countries.xsd");
dataSet.ReadXml("countries.xml");

countries.xsd:

<?xml version="1.0" standalone="yes"?>
<xs:schema id="Tables" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="countries" msdata:IsDataSet="true" msdata:MainDataTable="countries" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="country">
          <xs:complexType>
            <xs:attribute name="country_id" type="xs:int" msdata:AutoIncrement="true" msdata:AutoIncrementSeed="1"/>
            <xs:attribute name="name" type="xs:string" />
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

加载模式后,DataSet将具有名称countries和一个名为country的表。

  • 有两个表,因为xml文件中有两个复杂的xml元素:<countries><country>

  • 添加了额外的列"countries_id"(元素的Parent id)第二个表,以指定元素位于父id为"countries_id"=0的<countries>内。您可以在XML中再添加一个<countries>,并检查第二个表值中的"countries_id"父id"0"answers"1"。

`

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Tables xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <countries>
    <country country_id = "1" name = "Afghanistan"/>
    <country country_id = "2" name = "Albania"/>
    <country country_id = "3" name = "Algeria"/>
  </countries>
  <countries>
    <country country_id = "1" name = "Afghanistan"/>
    <country country_id = "2" name = "Albania"/>
    <country country_id = "3" name = "Algeria"/>
  </countries>
</Tables>

`