由于元素卡在元素上,无法解析XML

时间:2011-05-15 01:49:31

标签: c# xml xpath xml-namespaces

问题是ServiceDocument是xmlns属性。

---预先分配的XML

  System.Xml.XmlDocument xmlDoc = new XmlDocument();
  xmlDoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>
                    <ServiceDocument 
                      xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"
                      xmlns=\"http://schemas.microsoft.com/ado/2007/08/dataservices\"
                   >
                    <BaseUri>
                       http://xxxx.xxxxx.net/xxx.1/
                   </BaseUri>
                  <ProfilesLink>
                     http://adf.apis.dds.net/af.1/
                 </ProfilesLink>
                <SignedInUser>
                       <Cid>
                           4433sfsdfgd
                       </Cid>
                      <Uri>
                          http://fd.apis.afdafd.net/V4.1/cid-xxxxx/adad
                      </Uri>
               </SignedInUser> 
               <StatusMessageLink>
                      http://psm.adfa.afd.net/dfa.1/
               </StatusMessageLink>
            </ServiceDocument>"
            );
 // Response.Write(xmlDoc.InnerXml);

- // PARSE XML问题低于**

 Response.Write(xmlDoc.SelectSingleNode("/ServiceDocument/BaseUri").InnerXml);

1 个答案:

答案 0 :(得分:6)

您需要使用XMLNamespaceManager为命名空间指定短别名。

有关示例,请参阅this page

所以,要解决你的问题:

var xmlNamespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
xmlNamespaceManager.AddNamespace("ds", "http://schemas.microsoft.com/ado/2007/08/dataservices");
var result = xmlDoc.SelectNodes("/ds:ServiceDocument/ds:BaseUri", xmlNamespaceManager);