2017-02-09 8 views
2

私は、XMLファイルがあります:child1のXDocumentを使ってxml-fileを読むには?

のchild1の

コンテンツのrootcontentの

内容:私はメッセージを取得

 XDocument xml = XDocument.Load("D:\\test.xml"); 

     foreach (var node in xml.Descendants()) 
     { 
      if (node is XElement) 
      { 
       MessageBox.Show(node.Value); 
       //some code... 
      } 
     } 

<?xml version="1.0" encoding="UTF-8"?> 
    <root lev="0"> 
     content of root 
     <child1 lev="1" xmlns="root"> 
      content of child1 
     </child1> 
    </root> 

し、次のコードを

しかし、私はメッセージを必要とする:根の

コンテンツをchild1の

コンテンツどのようにそれを修正しますか?

+1

の可能性のある重複! [LINQ to XML - 子要素のテキストコンテンツを持たないXElementのテキストコンテンツを取得する(http://stackoverflow.com/questions/10302158/linq-to-xml-get-given-xelements-text-content-without-child- elements-text-con) – Fabio

答えて

0

代わりにforeach(XElement node in xdoc.Nodes())を試してください。要素の

1

文字列値は、(子要素の内側を含め、その中にあるすべてのテキストである

あなたはすべての非空のテキストノードの値を取得したい場合:。

XDocument xml = XDocument.Load("D:\\test.xml"); 

foreach (var node in xml.DescendantNodes().OfType<XText>()) 
{ 
    var value = node.Value.Trim(); 

    if (!string.IsNullOrEmpty(value)) 
    { 
     MessageBox.Show(value); 
     //some code... 
    } 
} 
+0

@CharlesMagerそれを指摘していただきありがとうございます。 – JLRishe

+0

良い答えですが、私はXElementにも必要です。 – SQLprog

+0

@SQLprogあなたは実際に何をしようとしているのかを明確にしていないので、これを超えて何を示唆するべきか分かりません。 – JLRishe

1

私はコードで結果を必要としてしまった:注意のため

XDocument xml = XDocument.Load("D:\\test.xml"); 

foreach (var node in xml.DescendantNodes()) 
{ 
    if (node is XText) 
    { 
     MessageBox.Show(((XText)node).Value); 
     //some code... 
    } 
    if (node is XElement) 
    { 
     //some code for XElement... 
    } 
} 

感謝

関連する問題