简体   繁体   中英

Can't parse XML because of the attribute stuck on element

The problem is the ServiceDocument as the xmlns attribute on it.

---Preassigned 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 problem is below**

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

You need to assign short aliases to the namespaces using the XMLNamespaceManager .

See this page for an example.

So, to solve your problem:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM