0

I want to read specific data from an XML file. This is what I have come up with so far: When I run my program without the (if (reader.Name == ControlID)) line reader.Value returns the right value,but when I include the if clause,it returns null

        public void GetValue(string ControlID)
    {
        XmlTextReader reader = new System.Xml.XmlTextReader("D:\\k.xml");
        string contents = "";

        while (reader.Read())
        {
            reader.MoveToContent();
            if (reader.Name == ControlID)
                contents = reader.Value;
        }
    }
Pedram
  • 728
  • 3
  • 10
  • 29

2 Answers2

1

Go through following code:

XmlDocument doc = new XmlDocument();
doc.Load(filename);
string xpath = "/Path/.../config"
foreach (XmlElement elm in doc.SelectNodes(xpath))
{
   Console.WriteLine(elm.GetAttribute("id"), elm.GetAttribute("desc"));
}

Using XPathDocument (faster, smaller memory footprint, read-only, weird API):

XPathDocument doc = new XPathDocument(filename);
string xpath = "/PathMasks/Mask[@desc='Mask_X1']/config"
XPathNodeIterator iter = doc.CreateNavigator().Select(xpath);
while (iter.MoveNext())
{
   Console.WriteLine(iter.Current.GetAttribute("id"), iter.Current.GetAttribute("desc'));
}

Can also refer this link:

http://support.microsoft.com/kb/307548

This might be helpful to you.

Freelancer
  • 9,008
  • 7
  • 42
  • 81
1

You can try the following code for example xPath query:

XmlDocument doc = new XmlDocument();
doc.Load("k.xml");

XmlNode absoluteNode;

/*
*<?xml version="1.0" encoding="UTF-8"?>
<ParentNode>
    <InfoNode>
        <ChildNodeProperty>0</ChildNodeProperty>
        <ChildNodeProperty>Zero</ChildNodeProperty>
    </InfoNode>
    <InfoNode>
        <ChildNodeProperty>1</ChildNodeProperty>
        <ChildNodeProperty>One</ChildNodeProperty>
    </InfoNode>
</ParentNode>
*/

int parser = 0
string nodeQuery = "//InfoNode//ChildNodeProperty[text()=" + parser + "]";
absoluteNode = doc.DocumentElement.SelectSingleNode(nodeQuery).ParentNode;

//return value is "Zero" as string
var nodeValue = absoluteNode.ChildNodes[1].InnerText; 
Gencebay
  • 61
  • 8