0

Hey I was wondering if anyone could help to save the value of my xml doc to a c# variable. It is to help with a larger program feature. The XML layout is:

<row>
    <var name="bud" value="45" />
    <var name="acc" value="345" />
</row>
<row>
    <var name="bud" value="45" />
    <var name="acc" value="345" />
</row>

I would like to extract the value of bud and store it as a string in my c# code

thanks for any help guys I appreciate it.

1
  • You're looking for LINQ to XML. Commented Dec 19, 2010 at 23:53

2 Answers 2

1

XML has to be valid so added a root element.

XML:

<foo>
 <row>
    <var name="bud" value="45" />
    <var name="acc" value="345" />
 </row>
 <row>
    <var name="bud" value="45" />
    <var name="acc" value="345" />
 </row>
</foo>

Code:

This will return a List with the values of all variables "var" in your XML named "bud" and finally create a comma separated string with all the values.

        string xml = "<foo><row><var name=\"bud\" value=\"45\" /><var name=\"acc\" value=\"345\" /></row><row><var name=\"bud\" value=\"45\" /><var name=\"acc\" value=\"345\" /></row></foo>";
        XDocument doc = XDocument.Parse(xml);
        var budValues =(from c in doc.Descendants("var") 
                       where c.Attribute("name").Value == "bud" 
                       select c.Attribute("value").Value).ToList();
        string myBuddy = string.Join(",", budValues);
Sign up to request clarification or add additional context in comments.

1 Comment

xml is...well..the xml you want to load, I added it so you can see.
1

Your xml is not valid. It requires a single root node.

Here is simple solution using XPath:

XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(@"
    <dataset><row>
        <var name=""bud"" value=""45"" />
        <var name=""acc"" value=""345"" />
    </row>
    <row>
        <var name=""bud"" value=""45"" />
        <var name=""acc"" value=""345"" />
    </row></dataset>");
XmlNode node = xDoc.SelectSingleNode("/dataset/row/var[@name='bud']");
string value = node.Attributes["value"].Value;

This gets only the first of the matches where @name='bud'. Checkout XPath to adjust your result. (it's pretty powerful)

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.