简体   繁体   中英

C# XML can no get sub-sub-sub node

i get a little complicated XML to fetch it is like:

<Response xmlns="http://somewhere/somewhere/">
<Params>
<Param>
<Name>some data</Name>
<Value xmlns="">abcdedsfeesfxyz0123456789</Value>
</Param>
<Param>
<Name>Target</Name>
<Value xmlns="">xml</Value>
</Param>
<Param>
<Name>Platform</Name>
<Value xmlns="">Mobile</Value>
</Param>
</Params>
<Results>
<Groups>
<Group>
<Key>ABCWXYZ0123456789</Key>
<TotalCount>1208</TotalCount>
<Useful>...</Useful>
</Group>
</Groups>
</Results>
</Response>

the useful data for me is in the the <Useful>...</Useful>

then i try to get the first layer:

    String returnXML = client.DownloadString(strUrl);
    XmlDocument xdoc = new XmlDocument();
    xdoc.LoadXml(returnXML);
    XmlNode xmlData = xdoc.SelectSingleNode("Response");

there is no data in xmlData

Thanks

The Response element has a default namespace defined.

<Response xmlns="http://somewhere/somewhere/">

You will need to resolve this namespace in the XPath expression you pass to SelectSingleNode. You can accomplish this using a XmlNamespaceManager:

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(returnXml);

var mng = new XmlNamespaceManager(xdoc.NameTable);
mng.AddNamespace("foo", "http://somewhere/somewhere/");

XmlNode xmlData = xdoc.SelectSingleNode("foo:Response",mng);

See MSDN: http://msdn.microsoft.com/en-us/library/h0hw012b.aspx and http://msdn.microsoft.com/en-us/library/d271ytdx.aspx

hmmm

i find this works!

XmlNodeList myElemList = xdoc.GetElementsByTagName("Usful");

You have to use an XmlNamespaceManager because you have namespaces declared (this line xmlns="http://somewhere/somewhere/" ).

See the answer to this question XmlNode in XmlNodelist

Understanding Xml namespaces will help you immensely. Try this article. http://www.jclark.com/xml/xmlns.htm

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