2013-04-08 3 views
0

XML 파일에서 특정 데이터를 읽으 려합니다. 이것은 내가 지금까지 생각 해낸 것입니다 : (if (reader.Name == ControlID)) 행 reader.Value를 사용하지 않고 프로그램을 실행하면 올바른 값을 반환하지만 if 절을 포함하면 반환됩니다. 널 (null)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

독자의 노드 이름은 컨트롤의 controlid과 같아야합니다. – Pedram

+2

XPath를 사용하려고 시도하십시오 – Killo

+0

@Killo 예를 제공해 주시겠습니까? – Pedram

답변

1

는 다음과 같은 코드를 통해 이동하여 XPathDocument 사용

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

(더 빨리, 더 작은 메모리 풋 프린트, 이상한 API 읽기 전용) :

이 당신에게 도움이 될 수

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

:

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

은이 링크를 참조 할 수 있습니다.

+0

내 친구에게 고맙다. 내 문제를 해결했다. – Pedram

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;