[英]How to read xml node names using C#
我是這個領域的新手。 請讓我知道如何獲取或顯示
書店,書,標題,價格(我需要的DISTINCT輸出)
從以下XML文件中,我如何讀取和打印DISTINCT xml節點。
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="en">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
使用Linq to XML很容易:
var xdoc = XDocument.Load(fileName);
var names = xdoc.Descendants() // get all elements from xml
.Select(e => e.Name.LocalName) // select local name of each element
.Distinct(); // pick only distinct names
對於你的樣本xml輸出是
[
"bookstore",
"book",
"title",
"price"
]
Descendants()
與XPathSelectElements("//*")
嘗試這個
public void Load()
{
var doc = XDocument.Load(filePath);
foreach(var unit in doc.Descendants("Unit"))
{
string str = string.Format("ID: {0}\r\nName:{0}", unit.Element("id").Value, unit.Element("name").Value);
MessageBox.Show(str);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.