【问题标题】:Can't parse XML because of the attribute stuck on element由于属性卡在元素上,无法解析 XML
【发布时间】:2011-05-15 01:49:31
【问题描述】:

问题在于 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);

【问题讨论】:

  • “属性”是默认命名空间声明。谷歌搜索“XPath 默认命名空间”,你会找到无数答案。

标签: c# xml xpath xml-namespaces


【解决方案1】:

您需要使用 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 2010-09-07
    • 1970-01-01
    • 2011-01-11
    • 2012-04-14
    • 1970-01-01
    相关资源
    最近更新 更多