これは、XDocumentを使用して解析されるXMLです。
<e xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FormValues />
<Others>
<Bank>
<Key>FirstKey</Key>
<Value>FirstValue</Value>
</Bank>
<Bank>
<Key>SecondKey</Key>
<Value>SecondValue</Value>
</Bank>
<Bank>
<Key>ThirdKey</Key>
<Value>ThirdValue</Value>
</Bank>
<Bank>
<Key>FourthKey</Key>
<Value>FourthValue</Value>
</Bank>
</Others>
<Prob>ProbValue</Prob>
<URL>http://example.com/</URL>
<Method>GET</Method>
</e>
私が行った場合:
string doc = "<e xmlns:xsd..> ..... </e>";
System.Xml.Linq.XDocument docNew = System.Xml.Linq.XDocument.Parse(doc);
var elements = docNew.Root.Descendants();
@foreach (var element in elements)
{
<label>@element.Name.ToString():</label><span>@element.Value.ToString()</span>
}
次のように表示されます。
FormValues:
Others: FirstKeyFirstValueSecondKeySecondValueThirdKeyThirdValueFourthKeyFourthValue
Bank : FirstKeyFirstValue
Key : FirstKey
Value: FirstValue
Bank : SecondKeySecondValue
Key : SecondKey
Value: SecondValue
Bank : ThirdKeyThirdValue
Key : ThirdKey
Value: ThirdValue
Bank : FourthKeyFourthValue
Key : FourthKey
Value: FourthValue
Prob : ProbValue
URL : http://example.com/
Method:GET
キーノードと値ノードにのみ値を表示させたい。お気に入り:
Others
Bank
Key : FirstKey
Value: FirstValue
Bank
Key : SecondKey
Value: SecondValue
....
XElement.Value
この要素のすべてのテキストコンテンツを含む文字列を返しますが、それぞれが直接所有するXText
子ノードの連結値のみを表示する必要があります。(これらは、要素の実際の文字データを保持するノードです。)XElement
これは次のように実行できます。
var docNew = System.Xml.Linq.XDocument.Parse(doc);
foreach (var element in docNew.Root.Descendants())
{
var textValue = string.Concat(element.Nodes().OfType<System.Xml.Linq.XText>().Select(tx => tx.Value));
Console.WriteLine(string.Format("{0}: {1}", element.Name.ToString(), textValue));
}
このロジックは、拡張メソッドに抽出できます。
public static partial class XNodeExtensions
{
public static string LocalValue(this XContainer node)
{
if (node == null)
return null;
return string.Concat(node.Nodes().OfType<XText>().Select(tx => tx.Value));
}
}
そして次のように使用されます:
var textValue = element.LocalValue();
以下を出力します。
FormValues:
Others:
Bank:
Key: FirstKey
Value: FirstValue
Bank:
Key: SecondKey
Value: SecondValue
Bank:
Key: ThirdKey
Value: ThirdValue
Bank:
Key: FourthKey
Value: FourthValue
Prob: ProbValue
URL: http://example.com/
Method: GET
ここでデモフィドル。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加