0

This is part of my XML file

<summary>
  <testcase>  
    <result value="-45">100</result>
    <result value="0">200</result>
    <result value="45">300</result>
  </testcase>
  <testcase>    
    <result value="-45">1000</result>
    <result value="0">2000</result>
    <result value="45">3000</result>
  </testcase>  
 <testcase>    
    <result value="-45">0.1</result>
    <result value="0">0.2</result>
    <result value="45">0.3</result>
  </testcase>
</summary>

I need to get element values by filtering by Attribute name.

As an Example I need to get all values where attribute = 45 Then Answer is 300,3000,0.3

XmlDocument doc = new XmlDocument();
doc.Load(_xmlFilePath);
XmlNodeList nodelist = doc.SelectNodes("//testcase");

for (int i = 0; i < nodelist.Count; i++)
{
    Double value;                        
    Double.TryParse(nodelist[i].SelectSingleNode("result").Attributes["45"].InnerText, out value);
    Console.WriteLine("value : " + value);
}

but above code gives following error message.

Object reference not set to an instance of an object.

Any suggestion is appreciate.

Thanks.

2 Answers 2

5

this may help you to solve your problem

XmlDocument doc = new XmlDocument();
doc.Load(_xmlFilePath);
XmlNodeList nodelist = doc.SelectNodes("//result[@value=45]");
for (int i = 0; i < nodelist.Count; i++)
{
    double value = double.Parse(nodelist[i].InnerText);
    Console.WriteLine("value : " + value);
}
Sign up to request clarification or add additional context in comments.

Comments

1

This might do the trick for you

XDocument xdc = XDocument.Load(YourXMLFile);
var rslt = xdc.Descendants("result").Where(x => x.Attribute("value").Value == "45");
string rsltstr = string.Empty;
foreach(XElement el in rslt)
{
    rsltstr = rsltstr + el.Value + ", ";
}

or

var rslt = xdc.Descendants("result")
              .Where(x => x.Attribute("value").Value == "45")
              .Select(q=>q.Value);

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.