How to query a peer XMLNode .NET
I h开发者_JAVA技巧ave an xml file. I want to query a peer node in C#.
For ex: For a given input xml file as below, i want to query the title using the artist as an input. How do i do this ?? i.e Input --> Pink Floyd, Output -----> Division Bell ..
<catalog>
<cd>
<title>Division Bell<title>
<artist>Pink Floyd<artist>
<price>29$<price>
</cd>
<cd>
<title>Relapse<title>
<artist>Eminem<artist>
<price>19$<price>
</cd>
</catalog>
You could use a XDocument:
using System;
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main()
{
var doc = XDocument.Load("test.xml");
var result =
(from cd in doc.Root.Descendants("cd")
let artist = cd.Element("artist")
let title = cd.Element("title")
where artist != null && title != null && artist.Value == "Pink Floyd"
select title.Value
).FirstOrDefault();
Console.WriteLine(result);
}
}
Its quite easy tor read xml in .net
XDocument loaded = XDocument.Load(@"C:\youxml.xml");
var query = from xElem in loaded.Descendants("cd")
where xElem.Element("artist").Value == "Eminem"
select new Friend
{
Title = xElem.Attribute("title").Value
};
Make use of Linq To XML or XLINQ will resolve you issue easily.
Also check this : http://msdn.microsoft.com/en-us/library/bb308960.aspx
You can also use XPath syntax.
here is an example:
string inputArtist = "Pink Floyd";
var doc = XDocument.Load("test.xml");
XmlNode cdTitleNode = doc.SelectSingleNode("//cd[artist='" + inputArtist + "']/title");
string outputTitle = cdTitleNode.InnerText;
There is an excellent XPATH simulator on http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm to try you Xpath expressions.
You can also found a good tutorial there, but a fast search on the web will result in many web pages explaining all about XPath usage and syntax.
Using XPath, you can return a match:
using System.Xml;
using System.Xml.XPath;
public string QuerySearch(string file, string artist) {
// create an XML Document and load the file
XmlDocument xd = new XmlDocument();
xd.Load(file);
// get the root xml element
XmlElement root = xd.DocumentElement;
// get the list of artists
XmlNodeList aristList = root.GetElementsByTagName("artist");
// get the list of titles's
XmlNodeList titleList = root.GetElementsByTagName("title");
// find match
for (int i = 0;i < aristList.Count; i++) {
if (aristList.Item(i).InnerText == artist) {
return titleList.Item(i).InnerText
}
}
return "no match found.";
}
精彩评论