开发者

How do I select a specifc node using System.Xml?

I have an XML document:

<Item>
   <ID>1</ID>
   <Title>Title1</Title>
   <Rank>1</Rank>
</Item>
<Item>
   <ID>2</ID>
    <Title>Title2</Title>
    <Rank>2</Rank>
</Item>

This document has ten items it, the problem I am having is that I will select the Title2 ID 2 and开发者_如何学C Rank 1.

 for (int i = 0; i < 10; i++)
 {
      XmlNode titleNode = doc.GetElementsByTagName("Title", NAMESPACE).Item(i);
      XmlNode asinNode = doc.GetElementsByTagName("ID", NAMESPACE).Item(i);
      XmlNode SalesNode = doc.GetElementsByTagName("SalesRank", NAMESPACE).Item(i);
 }

This is how I load the document.

            WebRequest request = HttpWebRequest.Create(url);
            WebResponse response = request.GetResponse();
            XmlDocument doc = new XmlDocument();
            doc.Load(response.GetResponseStream());


XmlNode node = doc.SelectSingleNode("/Item[ID='"+i.ToString()+"']");
XmlNode titleNode = node.SelectSingleNode("Title");
XmlNode asinNode = node.SelectSingleNode("ID");
XmlNode rankNode = node.SelectSingleNode("Rank");


You could use XML (de-)serialization: Just create a quick class for Item. full sample in XmlSerializer.Deserialize() docs.

Of course, this is just one among many techniques to parse XML (XPath, Linq to XML,...). Make your pick.


Here is a working example using XPath which I believe is what you really need.

let doc = XmlDocument()
doc.LoadXml ("<As><A><B>1</B></A><A><B>2</B></A></As>")
let n = doc.SelectSingleNode("As/A[B/text() = '1']")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜