在C#的LINQ解析混合XML到XML
问题描述:
<text>this is some text <content><link attr="someattr">text to appear in link</link></content> . this is the end of the text</text>
需要的XML元素转变成
<p>this is some text <a attr="someattr">text to appear in link</a> . this is the end of the text</p>
我有在“内容”元件采用作为参数并返回“的方法一个“元素。我无法弄清楚如何同时显示来自“text”元素和链接的文本。
答
你可以试试这个方法:
var xml =
@"<text>this is some text <content><link attr=""someattr"">text to appear in link</link></content> . this is the end of the text</text>";
var text = XElement.Parse(xml);
//change <text> to <p>
text.Name = "p";
var content = text.Element("content");
var link = content.Element("link");
//change <link> to <a>
link.Name = "a";
//move <a> to be after <content>
content.AddAfterSelf(link);
//remove <content> tag
content.Remove();
//print result
Console.WriteLine(text.ToString());
+0
这实际上工作,但当xml包含多个“内容”元素,然后我无法得到它的工作。 – 2014-09-11 22:37:36
+1
而不是使用content.Remove()删除元素,我试过text.Elements(“content”)。这是诀窍。我还在foreach循环中运行了前面的代码,以适当地添加“a”元素。 – 2014-09-11 23:14:15
我,你需要变换* *文本 - 也许LINQ到XML是不正确的方式去。您应该查看[RegularExpressions](http://msdn.microsoft.com/en-us/library/ms228595.aspx) – 2014-09-11 06:42:01
这不是文本而是xml。我只分享了xml的片段。 – 2014-09-11 22:36:08