在C#中从XML文件中读取特定数据

时间:2013-04-08 08:39:02

标签: c# xml

我想从XML文件中读取特定数据。 这是我到目前为止所提出的: 当我运行我的程序时没有(if(reader.Name == ControlID))行reader.Value返回正确的值,但是当我包含if子句时,它返回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;
        }
    }

2 个答案:

答案 0 :(得分:1)

浏览以下代码:

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"));
}

使用XPathDocument(更快,更小的内存占用,只读,奇怪的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'));
}

也可以参考此链接:

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

这可能对您有所帮助。

答案 1 :(得分:1)

您可以尝试以下代码,例如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;