2013-04-08 67 views
0

我想從XML文件讀取特定數據。 這是我到目前爲止: 當我運行我的程序沒有(if(reader.Name == ControlID))行reader.Value返回正確的值,但是當我包含if子句時,它返回空從C#中的XML文件中讀取特定數據

 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; 
     } 
    } 
+0

讀者的節點名稱必須與控件ID相等。 – Pedram 2013-04-08 08:40:00

+2

嘗試使用XPath – Killo 2013-04-08 08:40:24

+0

@Killo請你舉個例子嗎? – Pedram 2013-04-08 08:42:20

回答

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

這可能會對你有所幫助。

+0

謝謝我的朋友,這解決了我的問題 – Pedram 2013-04-08 08:52:34

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;