如何在 c# 2.0/3.0 上选择指定值的 xmlelements xmlnodes xmlattributes
Posted
技术标签:
【中文标题】如何在 c# 2.0/3.0 上选择指定值的 xmlelements xmlnodes xmlattributes【英文标题】:how to select xmlelements xmlnodes xmlattributes of specified values on c# 2.0/3.0 【发布时间】:2013-11-19 18:06:46 【问题描述】:这是我的 xml 文档,看起来像这样
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year updated="no" version="3.5">2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="fr">Harry Potter</title>
<author>J K. Rowling</author>
<year updated="yes" version="2.0">2005</year>
<price>29.99</price>
</book>
</bookstore>
1-如何选择所有books
并打印他们的element's text
(标题,作者,...)?
2-如何仅从year
获取每本书的lang
from
title
和version
的值?
3-如何选择所有books
where
category="cooking"
并打印所有元素?
4-如何选择title
的lang
为en
的所有书籍并打印其所有元素值?
【问题讨论】:
【参考方案1】:在这种情况下,这些版本的框架不支持XDocument
class
所以我们使用XmlDocument
XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.Load(@"c:\books.xml"); //wich is above you can use uri location
XmlNodeList list = myXmlDoc.SelectNodes("/bookstore/book");
//Selecting all book nodes then extract title author year
foreach (XmlNode mynode in list)
Console.WriteLine(mynode["title"].InnerText);
Console.WriteLine(mynode["author"].InnerText);
Console.WriteLine(mynode["year"].InnerText);
Console.WriteLine(mynode["price"].InnerText);
Console.WriteLine("------------");
//OUTPUT :
Everyday Italian
Giada De Laurentiis
2005
30.00
-----------------------
Harry Potter
J K. Rowling
2005
29.99
-----------------------
//get the value of `lang` from `title` and `version` from `year` :
foreach (XmlNode mynode in list)
Console.WriteLine(mynode["title"].Attributes["lang"].Value );
Console.WriteLine(mynode["year"].Attributes["version"].Value );
Console.WriteLine("------------");
//OUTPUT :
en
3.5
----------------
fr
2.0
//get books that have category="children" and print all both firstane lastname .....
XmlNodeList list = myXmlDoc.SelectNodes("/bookstore/book[@category='children']");
foreach (XmlNode mynode in list)
Console.WriteLine(mynode["title"].InnerText );
Console.WriteLine(mynode["author"].InnerText);
Console.WriteLine(mynode["price"].InnerText);
//OUTPUT:
Harry Potter
J K. Rowling
29.99
//select books where the `lang` of `title` is `en`
XmlNodeList list = myXmlDoc.SelectNodes("/bookstore/book/title[@lang='en']");
foreach (XmlNode mynode in list)
Console.WriteLine(mynode.ParentNode["title"].InnerText );
Console.WriteLine(mynode.ParentNode["author"].InnerText);
Console.WriteLine(mynode.ParentNode["price"].InnerText);
//OUTPUT:
Everyday Italian
Giada De Laurentiis
30.00
【讨论】:
以上是关于如何在 c# 2.0/3.0 上选择指定值的 xmlelements xmlnodes xmlattributes的主要内容,如果未能解决你的问题,请参考以下文章