Flob
Flob

Reputation: 128

How to find a specific XML tag in .NET C#

Suppose I have this XML file:

<?xml version="1.0" encoding="utf-8" ?>
<config>
  <atag>
    <element1 att="value" />
    <element2 att="othervalue"/>
  </atag>
  <othertag>
    <element1 att="value" />
    <element2 att="othervalue"/>
  </othertag>
</config>

What is the best way to access the attribute att in <element2> under <othertag>.

I'm currently using this:

XmlDocument doc = new XmlDocument();
String srR = SPContext.Current.Web.Url.ToString() + "config.xml";
WebRequest refF = WebRequest.Create(srR);
refF.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse resFF = (HttpWebResponse)refF.GetResponse();
doc.Load(resFF.GetResponseStream());
XmlNodeList nodes = doc.GetElementsByTagName("othertag");

XmlNode ParentNodes = nodes[0];
foreach (XmlNode ParentNode in ParentNodes.ChildNodes) 
{
    if (ParentNode.LocalName == "element2")
    {
        string value = ParentNode.Attributes["att"].InnerText.ToString();
    }
}

It is doing the job, but I think it's too heavy, specially that I'm using it on an ashx file that is loaded whenever I change a value in a dropdown and the XML file is very large (around ~155kb).

Is there any way to improve this?

Upvotes: 2

Views: 2279

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500465

I would use LINQ to XML - something like this:

XDocument doc = XDocument.Load(...);
var attribute = doc.Element("config")
                   .Element("othervalue")
                   .Element("element2")
                   .Attribute("att");

var attributeValue = (string) attribute;

Note that this will fail if any of the elements are missing - an alternative which would return null at the end for any failures would be:

var attribute = doc.Elements("config")
                   .Elements("othervalue")
                   .Elements("element2")
                   .Attributes("att")
                   .FirstOrDefault();

var attributeValue = (string) attribute;

If you're new to LINQ to XML, you should read a full tutorial or something similar rather than just using the code above. It's a fabulous API though - much nicer than XmlDocument.

Upvotes: 8

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

You can use XPath: //othertag/element2/@att or XDocument with LINQ.

Upvotes: 1

thekip
thekip

Reputation: 3768

You can use xpath or linq to. Xml for this. See w3.org or msdn And for the size issue you shoud use an xpathdocument with an xpathnavigator.

Upvotes: 0

Related Questions