使用XElement解析XML会导致Object引用未设置为对象的实例

时间:2014-03-16 18:50:08

标签: c# asp.net

以下XML是从Web服务返回的。但是,我似乎无法获得或使用XElement时的值。

<ResponseArray xmlns="urn:mdWebServiceAddress" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Version>2.0.62</Version>
  <TransmissionReference></TransmissionReference>
  <Results></Results>
  <TotalRecords>1</TotalRecords>
  <Record>
    <RecordID>1</RecordID>
    <Results>AC01,AS01</Results>
    <Address>
      <Address1>22382 Avenida Empresa</Address1>
      <Address2></Address2>
      <Suite></Suite>
      <PrivateMailBox></PrivateMailBox>
      <City>
        <Name>Rancho Santa Margarita</Name>
        <Abbreviation>Rcho Sta Marg</Abbreviation>
      </City>
      <State>
        <Name>California</Name>
        <Abbreviation>CA</Abbreviation>
      </State>
      <Zip>92688</Zip>
      <Plus4>2112</Plus4>
      <AddressKey>92688211282</AddressKey>
    </Address>
  </Record>
</ResponseArray>

以下是我用来收集值的代码。命名空间设置不正确吗?如何在XML中访问这些元素的值。

        XElement xelement = XElement.Parse(xmlString);
        XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";

        IEnumerable<XElement> records = xelement.Elements();

        foreach (var record in records)
        {
            Console.WriteLine(record.Element(ns + "RecordID").Value);
            Console.WriteLine(record.Element(ns + "Address").Element(ns + "AddressKey").Value);
        }

1 个答案:

答案 0 :(得分:0)

a)更改命名空间

b)使用后代

XNamespace ns = "urn:mdWebServiceAddress";

IEnumerable<XElement> records = xelement.Descendants(ns + "Record");

foreach (var record in records)
{
    Console.WriteLine(record.Element(ns + "RecordID").Value);
    Console.WriteLine(record.Element(ns + "Address").Element(ns + "AddressKey").Value);
}

PS:使用xml命名空间的安全方法可以是

XNamespace ns = xelement.GetDefaultNamespace();