Performing XPath Queries on documents with default namespaces [duplicate]
Possible Duplicate:
Using Xpath With Default Namespace in C#
Hello,
I'm having a hard time doing xpath on diabolical XML for an integration component. The problem is that some nodes are namespace prefixed and other aren't.
I have a sample XML that declares a default ns and then some particular NS's for other element:
<?xml version="1.0" encoding="UTF-8"?>
<Header xmlns="http://namespaceFoo.com">
<MessageID>1300121668281</MessageID>
<OriginIdentificaton>
<Code>2050302</Code>
</OriginIdentificaton>
<PatientData>
<n开发者_运维知识库s1:Identificacao xmlns:ns1="http://namespaceBAR.com">
<ns1:SSN>123456789</ns1:SSN>
<ns1:Name>Johnny john</ns1:Name>
</ns1:Identificacao>
<ns2:Diagnosis xmlns:ns2="http://namespaceBAR.com"/>
<ns3:Contacts xmlns:ns3="http://namespaceBAR.com"/>
<ns4:Benefits xmlns:ns4="http://namespaceBAR.com"/>
</PatientData>
</Header>
And I'm trying to query it with something like:
XmlDocument xmlData = new XmlDocument and LoadXml()
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(xmlData.NameTable);
xmlnsManager.AddNamespace(String.Empty, "http://namespaceFoo.com");
XmlNode n1 = xmlData.SelectSingleNode("/Header");
Which returns Null.
I'm totally lost. I've tried several combinations of namespaces and xpath queries to no avail.
Shouldn't this be trivially simple? Is there a way to query "/Element1/Element2/..." regardless of the namespace of these elements?
Thanks
You're so close! You need to first give your empty namespace a "fake" prefix (first line below) and then pass the XmlNamespaceManager into the SelectSingleNode function.
xmlnsManager.AddNamespace("x", "http://namespaceFoo.com");
XmlNode n1 = xmlData.SelectSingleNode("/Header", xmlnsManager);
精彩评论