Kluny
Kluny

Reputation: 189

I want to read a single element of an XML file and output it to an aspx control

My XML looks like this:

<product id="1">
    <name>A thing</name>
    <description>This is what it's like</description>
</product>

I've been looking for an example that might look something like this:

string productID = 1;
XDocument productsXML = XDocument.Load("Products.xml");
for item in productsXML {
    if (item.ID == productID) {
        productNameLabel.Text = item.name;
    }
}

The idea being, I'll be able to output a single xml child element to the .aspx page.

A thing

Does that make sense? I've been looking for examples for a few hours, and I'm starting to think that there is lot more scaffolding that I need, but since all the examples are so different, I'm not sure which one to follow!

So, how can I grab the contents of a single XML child element, and output it to the .aspx? Take this:

<product id="1">
    <name>A thing</name>
    <description>This is what it's like</description
</product>

and output this:

A thing

Upvotes: 2

Views: 2703

Answers (2)

Mike Cofoed
Mike Cofoed

Reputation: 151

In this case, I agree with L.B.'s answer since it is rather simple. If you like Linq (I noticed you were using XDocument, which is a Linq to XML object), here's an alternative solution:

XDocument productsXML = XDocument.Load("Products.xml");
        string item = productsXML.Elements("product")
                                 .Where(p => p.Attribute("id").Value == productID)
                                 .First()
                                 .Element("name").Value;

productsXML.Elements("product") This gets all product nodes in the document.
.Where(p => p.Attribute("id").Value == productID) This gets only the product node(s) with the id that matches your productiD.
.First() Since the .Where function returns a collection of nodes, this grabs the first one.
.Element("name").Value; This finds an element within the product node called name and returns its value.

For such a simple schema, the XPath seems much less verbose, but a bit harder to understand if you don't know XPath in the first place. Linq is a lot more lines of code (in this instance), but is a lot more readable if you don't know XPath.

Upvotes: 0

L.B
L.B

Reputation: 116118

You can use XPath (in System.Xml.XPath)

string value = productsXML.XPathSelectElement("//product[@id='1']/name").Value;

Upvotes: 2

Related Questions