1

I have an XML file as follow

<NODE1 attribute1 = "SomeValue" attribute2 = "SomeOtherValue" />
<NODE2 attribute3 = "SomeValue" attribute4 = "SomeOtherValue" />

Now I am given only the attribute name say "attribute3". How can I get the name of node?

0

3 Answers 3

1

Add the following namespace at the top of your file:

using System.Xml.Linq;

And try this (assuming that input.xml is the path to your XML file):

var xml = XDocument.Load("input.xml");
string nodeName;
var node = xml.Descendants()
    .FirstOrDefault(e => e.Attribute("attribute3") != null);
if (node != null)
    nodeName = node.Name.LocalName;
Sign up to request clarification or add additional context in comments.

Comments

1

With LINQ to XML:

XDocument xdoc = XDocument.Load(path_to_xml);
var nodes = xdoc.Descendants().Where(e => e.Attribute("attribute3") != null);

Or with XPath (as Marvin suggested):

var nodes = xdoc.XPathSelectElements("//*[@attribute3]");

Both queries will return collection of XElement nodes which have attribute attribute3 defined. You can get first of them with FirstOrDefault. If you want to get just name, use node.Name.LocalName.

UPDATE: I do not recommend you to use XmlDocument, but if you already manipulating this xml document, then loading it second time with XDocument could be inefficient. So, you can select nodes with XPathNavigator:

var doc = new XmlDocument();
doc.Load(path_to_xml);
var naviagator = doc.CreateNavigator();            
var nodeIterator = naviagator.Select("//*[@attribute3]");

3 Comments

I am already using XmlDocument to load XML and perform some other tasks.
Can I use both XMLDocument and XDocument
@imvarunkmr it's better to use XDocument if you are using .NET Framework 3 or later versions
0

try in this way

    string nodeName;
    if(Node.Attributes.Cast<XmlAttribute>().Any(x => x.Name == "attribute3"))
    {
        nodeName=Node.Name;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.