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 に答える