-1

I'm starting working with XML files and I know little about it.

What I need is read the value from a certain tag of a XML file

<Tag>
<Name>PBAS</Name>
<ID>1</ID>
<Description>Array of sequence characters as edited by user</Description>
<Type>char</Type>
<Elements>163</Elements>
<Size>163</Size>
    <Value>TCCGAACAAGCGGCGAGTGCTGGGCGAGTGGCCGCGGGGCTGTGGTCCTGTGCACGGTGATCGCAAGGGCCCCCGGGGCTTGCTGGTCTTCCCTAACGGTTCGTGGAACCCCCGAAGCTGGGGGCTGGCCAGGGGCTTAAGGAACCCTTCCTAAATTAACTAC</Value>
</Tag>

I need, in the example above, getting the string between the "Value"(the string TCCGA...) of the tag named "PBAS" with "ID 1".

But I need this value just from the tag named PBAS with "ID1", since the XML document has other "values" from other tags named differently.

Thanks a lot!

D Stanley
  • 149,601
  • 11
  • 178
  • 240
anderici
  • 77
  • 1
  • 11

3 Answers3

3
var yourval = XDocument.Load(filename)
                .XPathSelectElement("//Tag[Name='PBAS' and ID='1']")
                .Element("Value")
                .Value;

or

var yourval = (string)XDocument.Load(filename)
                      .XPathSelectElement("//Tag[Name='PBAS' and ID='1']/Value");

or (using only Linq)

var yourval = XDocument.Load(filename)
              .Descendants("Tag")
              .Where(t => (string)t.Element("Name") == "PBAS")
              .Where(t => (string)t.Element("ID") == "1")
              .First()
              .Element("Value")
              .Value;

PS: Necessary namespaces: System.Xml, System.Xml.XPath, and System.Xml.Linq . Also Read about Linq2Xml and Xpath

EZI
  • 15,209
  • 2
  • 27
  • 33
1

The technology to select nodes from XML is called XPath. Basically you create a path of element names separated by / like

/Tag/Value

To specify conditions, put them in square brackets at the place from where you want to start the condition:

/Tag[./Name/text()="PBAS"][./ID/text()="1"]/Value

Above XPath is good for demonstration purposes, since it explains how it works. In practice, this would be simplified to

/Tag[Name="PBAS"][ID="1"]/Value

Code:

using System.Xml;

var doc = new XmlDocument();
doc.LoadXml(xml);
var nodes = doc.SelectNodes("/Tag[./Name/text()=\"PBAS\"][./ID/text()=\"1\"]/Value");
foreach (XmlElement node in nodes)
{                
    Console.WriteLine(node.InnerText);
}
Console.ReadLine();
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
0

You can use the below code:

string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(xmlFile);
                XmlNodeList xnList = xmldoc.SelectNodes("/Tag");
                string Value ="";
foreach (XmlNode xn in xnList)
{
  string ID = xn["ID"].InnerText;
  if(ID =="1")
  {
  value = xn["Value"].InnerText;
  }
}
  • Assuming that you put the contents of the xml file in the file with the specified path : D:\Work_Time_Calculator\10-07-2013.xml – Mohamed Ragab Jul 15 '15 at 22:43