I'm trying to parse the following:
<?xml version="1.0" encoding="utf-8"?>
<GC>
<CREATED>01/23/2014 16:10:18</CREATED>
<DATA>
<CONTAINER name="home" type="xml" version="1.1.0.0">
<HEADER>
<ATTRIBUTE name="lang" value="EN" />
<ATTRIBUTE name="destination" value="UK" />
</HEADER>
</CONTAINER>
</DATA>
</GC>
How do I go about finding the value when name="lang" ?
So far I have this:
XmlDocument Doc = new XmlDocument();
Doc.Load(@path);
XmlNode node = Doc.DocumentElement.SelectSingleNode("/GC/DATA/CONTAINER/HEADER/ATTRIBUTE/NAME");
string SI = node.Attributes["lang"].InnerText;
Doesn't seem to work unfortunately, could use some help. Many thanks.
With using LINQ to XML
you can get it like this:
XDocument xDoc = XDocument.Load("path");
var element = xDoc.Descendans("ATTRIBUTE").First();
var nameAttribute = (string)element.Attribute("name");
This will get you the value of the attribute in the ATTRIBUTE tag which has name == lang:
XmlDocument Doc = new XmlDocument();
Doc.Load(@path);
XmlNode node = Doc.DocumentElement.SelectSingleNode("/GC/DATA/CONTAINER/HEADER/ATTRIBUTE[@name='lang']");
string SI = node.Attributes["value"].InnerText;
XmlNode node = Doc.DocumentElement.SelectSingleNode("/GC/DATA/CONTAINER/HEADER/ATTRIBUTE[@name='lang']");
string SI = node.Attributes["value"].Value;
This will do it:
XmlNode node =
Doc.SelectSingleNode("/GC/DATA/CONTAINER/HEADER/ATTRIBUTE[@name = 'lang']/@value");
string SI = node.InnerText;
And I would advise using a null check:
XmlNode node =
Doc.SelectSingleNode("/GC/DATA/CONTAINER/HEADER/ATTRIBUTE[@name = 'lang']/@value");
string SI = null;
if(node != null)
{
SI = node.InnerText;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.