I am trying to get the node names based on the attribute values, but I am not able to proceed much on this, if anyone can help me on this.
I have the sample xml as below:
<ns0:Person xmlns:ns0="http://temp.poc">
<name>
<value>temp</value>
<status>T</status>
</name>
<age>
<value>tempval</value>
<status>F</status>
</age>
<cellNumber>
<value>9971760613</value>
<status>T</status>
</cellNumber>
<city>
<value>Bangalore</value>
<status>F</status>
</city>
<ApplicationAccess>
<value>value_0</value>
<status>T</status>
</ApplicationAccess>
</ns0:Person>
Based on the Status , where status = "T" , I need the node names as output. for eg :
assistant
cellNumber
ApplicationAccess
You can achieve that using XmlDocument
and XPath
, like this:
string xml = @"
<ns0:Person xmlns:ns0='http://temp.poc'>
<name>
<value>temp</value>
<status>T</status>
</name>
<age>
<value>tempval</value>
<status>F</status>
</age>
<cellNumber>
<value>9971760613</value>
<status>T</status>
</cellNumber>
<city>
<value>Bangalore</value>
<status>F</status>
</city>
<ApplicationAccess>
<value>value_0</value>
<status>T</status>
</ApplicationAccess>
</ns0:Person>";
var doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList nodes = doc.SelectNodes("//status[text() ='T']");
foreach (XmlNode node in nodes)
{
Console.WriteLine(node.ParentNode.Name);
}
output will be names of those nodes whose child node status
has T
as innerText.
name
cellNumber
ApplicationAccess
Using XDocument
(which I prefer over XmlDocument
):
var root = XDocument.Load(...).Root; // the <ns0:Person> XElement
var namesOfElementWithStatusT = root.Elements()
.Where(e => e.Elements().Any(e1 => e1.Name == "status" && e1.Value == "T"))
.Select(e => e.Name.LocalName)
.ToList();
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.