Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading specific XML elements from XML file

Tags:

c#

xml

I have the following XML file

<lexicon> <word>   <base>a</base>   <category>determiner</category>   <id>E0006419</id> </word> <word>   <base>abandon</base>   <category>verb</category>   <id>E0006429</id>   <ditransitive/>   <transitive/> </word> <word>   <base>abbey</base>   <category>noun</category>   <id>E0203496</id> </word> <word>   <base>ability</base>   <category>noun</category>   <id>E0006490</id> </word> <word>   <base>able</base>   <category>adjective</category>   <id>E0006510</id>   <predicative/>   <qualitative/> </word> <word>   <base>abnormal</base>   <category>adjective</category>   <id>E0006517</id>   <predicative/>   <qualitative/> </word> <word>   <base>abolish</base>   <category>verb</category>   <id>E0006524</id>   <transitive/> </word> </lexicon> 

I need to read this file with C# application, and if only the category is verb I want to print its entire element word.
How can I do that?

like image 482
Ruba Avatar asked Jan 01 '13 11:01

Ruba


People also ask

How do I read text in XML?

View an XML file in a browser If all you need to do is view the data in an XML file, you're in luck. Just about every browser can open an XML file. In Chrome, just open a new tab and drag the XML file over. Alternatively, right click on the XML file and hover over "Open with" then click "Chrome".

What is fetch data from XML file?

The page uses the XMLHttpRequest (JavaScript) object to fetch the XML file (sample. xml) then parses it in JavaScript and creates the chart. The function that parses the XML response and then uses the data to create the chart is shown below and called myXMLProcessor() (it's the XMLHttpRequest callback function).


2 Answers

You could use linq to xml.

    var xmlStr = File.ReadAllText("fileName.xml");       var str = XElement.Parse(xmlStr);      var result = str.Elements("word"). Where(x => x.Element("category").Value.Equals("verb")).ToList();      Console.WriteLine(result); 
like image 167
scartag Avatar answered Sep 18 '22 15:09

scartag


You could use an XPath, too. A bit old fashioned but still effective:

using System.Xml;  ...  XmlDocument xmlDocument;  xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml);  foreach (XmlElement xmlElement in      xmlDocument.DocumentElement.SelectNodes("word[category='verb']")) {     Console.Out.WriteLine(xmlElement.OuterXml); } 
like image 38
akton Avatar answered Sep 22 '22 15:09

akton