2013-04-08 84 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;