![](/img/trans.png)
[英]How to get same element value from xml which having same and different nodes using linq in c#
[英]How to get value of same nodes in XML in c#
<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<price>10.90</price>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<price>10.0</price>
</cd>
<cd>
<title>Greatest Hits</title>
<artist>Bob Dylan</artist>
<price>10.90</price>
</cd>
</catalog>
根據需要調整它...
using System.Xml;
static void GetArtistFromXml()
{
var xml = "<?xml version=\"1.0\" encoding=\"ISO - 8859 - 1\"?><catalog><cd><title>Empire Burlesque</title><artist>Bob Dylan</artist><price>10.90</price></cd><cd><title>Hide your heart</title><artist>Bonnie Tyler</artist><price>10.0</price></cd><cd><title>Greatest Hits</title><artist>Bob Dylan</artist><price>10.90</price></cd></catalog>";
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
var artistElement = xmlDocument.DocumentElement.SelectSingleNode("//cd[title[text()=\"Greatest Hits\"]]/artist");
Console.WriteLine(artistElement.InnerText);
}
最好使用LINQ 到 XML API。 它自 2007 年起在 .Net Framework 中可用。
c#
void Main()
{
const string filename = @"e:\Temp\AmeyP.xml";
XDocument xdoc = XDocument.Load(filename);
string artist = xdoc.Descendants("cd")
.Where(x => x.Element("title").Value.Equals("Greatest Hits"))
.Elements("artist").FirstOrDefault()?.Value;
Console.WriteLine(artist);
}
Output鮑勃·迪倫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.