开发者

Searching elements in a XML

I have a similar XML file which i required to search for its values .. as if for example when the Product Name is entered relevant price should be displayed

if there a easy way than parsing and search for values by loops ?

<products>
    <product>
      <Name> PRODUCT 1</Name>
      <price>150</price>
    </product>
    <product>
      <Name> PRODUCT 2</N开发者_JS百科ame>
      <price>250</price>
    </product>
    <product>
      <Name> PRODUCT 3</Name>
      <price>300</price>
    </product>
  <products>


You can use XPath:

XmlDocument doc = new XmlDocument();
doc.Load("myfile.xml");
XmlNode myPrice = doc.SelectSingleNode("/products/product[Name=' PRODUCT 1']/price");
Console.WriteLine(myPrice.InnerText);

outputs

150

Note that the whitespace before your product identifiers is significant.

You can do the same thing using XPathDocument, if you prefer:

XPathDocument doc = new XPathDocument("myfile.xml");
XPathNavigator xpath = doc.CreateNavigator();
XPathNavigator myPrice = xpath.SelectSingleNode("/products/product[Name=' PRODUCT 1']/price");
Console.WriteLine(myPrice.ToString());

also outputs

150

Tested both of these in .NET 2.0.


Linq to Xml is another possible solution that should minimise processing to the task at hand see msdn for more details: http://msdn.microsoft.com/en-us/library/bb387085.aspx

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜