为什么在使用ReadXml的C#中加载DataSet为空?

我正在使用C#4.5 / Visual Studio 2012尝试将
XML文件加载到DataSet.我在这里阅读说明:

http://msdn.microsoft.com/en-us/library/fx29c3yd.aspx

我正在加载一个如下所示的XML文件:

<?xml version="1.0" encoding="utf-8" ?>

<UnitTestDataSet xmlns="https://rebuildinghomes.codeplex.com/" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="https://rebuildinghomes.codeplex.com/ UnitTestLoadData.xsd">
  <Person>
    <PersonId>1111</PersonId>
    <FirstName>Unit</FirstName>
    <LastName>Tester</LastName>
  </Person>
</UnitTestDataSet>

使用这样的架构:

<?xml version="1.0" encoding="utf-8" ?>

<xs:schema id="RebuildingUnitTestData"
            targetNamespace="https://rebuildinghomes.codeplex.com/"
            xmlns:u="https://rebuildinghomes.codeplex.com/"
            elementFormDefault="qualified"
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:complexType name="PersonType">
    <xs:sequence>
      <xs:element name="PersonId" type="xs:int"
                   minOccurs="1" maxOccurs="1" />
      <xs:element name="FirstName" type="xs:string"
                   minOccurs="1" maxOccurs="1" />
      <xs:element name="LastName" type="xs:string"
                   minOccurs="1" maxOccurs="1" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>

使用以下C#代码:

        //Load init/expected
        DataSet init = new DataSet();

        init.ReadXmlSchema("RebuildingModel/Data/UnitTestLoadData.xsd");

        init.ReadXml("RebuildingModel/Data/PersonUnitTest.xml", XmlReadMode.ReadSchema);

但是,当我在调试器中查看“init”时,DataSet为空.我究竟做错了什么?

最佳答案 可悲的是,你的代码片段似乎可以在我的机器上运行.你确定你在init.ReadXml()语句执行后检查init吗?

从下面的Visual Studio立即窗口中查看我的输出:

ds.Tables[0]
{Person}
    base {System.ComponentModel.MarshalByValueComponent}: {Person}
    CaseSensitive: false
    ChildRelations: {System.Data.DataRelationCollection.DataTableRelationCollection}
    Columns: {System.Data.DataColumnCollection}
    Constraints: {System.Data.ConstraintCollection}
    DataSet: {System.Data.DataSet}
    DefaultView: {System.Data.DataView}
    DisplayExpression: ""
    ExtendedProperties: Count = 0
    HasErrors: false
    IsInitialized: true
    Locale: {en-US}
    MinimumCapacity: 50
    Namespace: "https://rebuildinghomes.codeplex.com/"
    ParentRelations: {System.Data.DataRelationCollection.DataTableRelationCollection}
    Prefix: ""
    PrimaryKey: {System.Data.DataColumn[0]}
    RemotingFormat: Xml
    Rows: {System.Data.DataRowCollection}
    Site: null
    TableName: "Person"
ds.Tables[0].Rows
{System.Data.DataRowCollection}
    base {System.Data.InternalDataCollectionBase}: {System.Data.DataRowCollection}
    Count: 1

根据您的XML,我的DataSet填充了一个包含单行的表.

点赞