2012-01-17 20 views
1

以下はmy xmlドキュメントの構造です。私はちょうど最初にすべてのノードの価値を取って、それから与えられた値との比較をしたいと思います。しかし、私はどのように各ノードのを見つけるためにC#でxmlのselectnodesを使用していません。 Googleの検索では、実際のソリューションは表示されません。 XMLへ特殊なxml構造のname属性名を持つ要素を選択

<nodes>  
<node name = "node1">  
    <attribute name="a">This is node1 a</attribute> 
    <attribute name="b">This is node1 b</attribute> 
</node> 
<node name = "node2">  
    <attribute name="a">This is node2 a</attribute> 
    <attribute name="b">This is node2 b</attribute> 
</node> 
... 
</nodes>  

答えて

1

があなたの文書全体を表し、あなたが行うことができます:

XmlNodeList attrElements 
    = yourDocument.SelectNodes("/nodes/node/attribute[@name='a']"); 
3

利用のLINQ:

XElement xml = XElement.Load("test.xml"); 
var myNodes = xml.Descendants("attribute") 
       .Where(x => x.Attribute("name").Value == "a"); 

代わりにノードの値を取得する:あなたの質問内のXMLマークアップを想定し

var myValues = xml.Descendants("attribute") 
        .Where(x => x.Attribute("name").Value == "a") 
        .Select(x => x.Value); 
+0

consolewriteline(myvalues)を取得していることを確認するために、いくつかのXPathの参照を見ている必要があります:私が得た:System.Linq.Enumerable + WhereSelectEnumerableIterator' 2 [System.Xml.Linq.XElement、 可能System.String] – user1154138

+0

あなたはアイテムではない列挙をプリントアウトする必要があります: 'foreachの(myValues中のvarアイテム)Console.WriteLineを(項目);' – BrokenGlass

1

次のようなLinqからXMLを使用します。

string xml = "<nodes>..."; 

var results = from node in XDocument.Parse(xml).Descendants() 
      where node.Name == "attribute" 
      select node.Value; 

必要に応じて結果をループすることができます。

Linq to XML overview hereもあります。

1

私は私のXML解析のためのSystem.Xml.XmlDocumentクラスを使用するようにしたいです。

XmlDocument doc = new XmlDocument(); 
doc.load("myfilename.xml"); 
XmlNode node = doc.SelectSingleNode("\\attribute[name='a']") 

あなたは妙に動作しますが、XPath文字列を右http://msdn.microsoft.com/en-us/library/ms256086.aspx

関連する問題