0

我想从 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;
        }
    }
4

2 回答 2

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

这可能对您有帮助。

于 2013-04-08T08:50:25.930 回答
1

您可以尝试以下代码,例如 xPath 查询:

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; 
于 2013-04-08T08:56:03.233 回答