遍历XmlElement的Children(SelectSingleNode返回NULL)

时间:2013-07-11 22:21:45

标签: c# xml xmldocument

我正在尝试遍历XML元素并将值分配给对象的成员变量。以下是我的尝试。但是SelectSingleNode()正在返回NULL。 data.Any是一个XmlElement数组(由服务返回)。我尝试使用XmlNamespaceManager,但data.Any不是XmlDocument,因此它不包含NameTable。我究竟做错了什么?

CODE:

foreach (XmlElement item in data.Any)
{
    result.CorrelationID = item.SelectSingleNode("CorrelationID").InnerText;
}

XML:

<CorrelationID xmlns="http://www.host.com/folder/anotherFolder">9B36D7A7EDD26A22</CorrelationID>
<EmployerRef xmlns="http://www.host.com/folder/anotherFolder">1235/AN612</EmployerRef>
<Name xmlns="http://www.host.com/folder/anotherFolder">
<Ttl>MS</Ttl>
<Fore>NameFirst</Fore>
<Sur>NameLast</Sur>
</Name>
<PayId xmlns="http://www.host.com/folder/anotherFolder">FLDA/12</PayId>
<NINOToUse xmlns="http://www.host.com/folder/anotherFolder">SL3747A</NINOToUse>
<MessageID xmlns="http://www.host.com/folder/anotherFolder">3</MessageID>

1 个答案:

答案 0 :(得分:1)

foreach (XmlElement item in data.Any)
{
    XmlDocument doc = item.OwnerDocument;
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
    nsmgr.AddNamespace("af", "http://www.host.com/folder/anotherFolder");
    result.CorrelationID = item.SelectSingleNode("af::CorrelationID", nsmgr).InnerText;
}