以下に素晴らしい XML の例を示します。
<root>
<section>Here is some text<mightbe>a tag</mightbe>might <not attribute="be" />. Things are just<label>a mess</label>but I have to parse it because that's what needs to be done and I can't <font stupid="true">control</font> the source. <p>Why are there p tags here?</p>Who knows, but there may or may not be spaces around them so that's awesome. The point here is, there's node soup inside the section node and no definition for the document.</section>
</root>
セクション ノードとすべてのサブ ノードからテキストを文字列として取得したいと思います。ただし、サブノードの周りにスペースがある場合とない場合があることに注意してください。そのため、サブノートを埋めてスペースを追加したいと考えています。
入力がどのように見えるか、および出力をどのようにしたいかのより正確な例を次に示します。
<root>
<sample>A good story is the<book>Hitchhikers Guide to the Galaxy</book>. It was published<date>a long time ago</date>. I usually read at<time>9pm</time>.</sample>
</root>
出力を次のようにしたい:
A good story is the Hitchhikers Guide to the Galaxy. It was published a long time ago. I usually read at 9pm.
子ノードの周りにスペースがないことに注意してください。そのため、それらをパディングする必要があります。そうしないと、単語が一緒に実行されます。
私はこのサンプルコードを使用しようとしていました:
XDocument doc = XDocument.Parse(xml);
foreach(var node in doc.Root.Elements("section"))
{
output += String.Join(" ", node.Nodes().Select(x => x.ToString()).ToArray()) + " ";
}
しかし、出力には子タグが含まれており、うまくいきません。
ここに何か提案はありますか?
TL;DR: ノード スープ xml が与えられ、子ノードの周囲にパディングを付けて文字列化したいと考えています。