我有一个以下格式的 xml 文档:
<body>
<par id = "1">
<prop type="Content">One</prop>
<child xml:id="1">
<span>This is span 1</span>
</child>
<child xml:id="2">
<span>This is span 2</span>
</child>
</par>
</body>
我对使用 LINQ 不太熟悉,我想用它来交换上面代码的元素。 (即,我想搬家
<span>This is span 2</span>
进入
<child xml:id="1"></child>
元素树,反之亦然)
我正在运行 http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b 处的示例,但我真的很想朝正确的方向进一步插入(老实说,我不知道从哪里开始!)。
谢谢!
最佳答案
您可以使用 Linq to sml 查询选择特定元素
var retmodule = (from c in xdoc.Elements("body").Elements("par").Elements("child").
where c.Attribute("xml:id").Value == 2
select new
{
c.Element("span").Value
}).SingleOrDefault();
然后使用xpath和xml库结合插入
XElement parentXElement = xmldoc.XPathSelectElement("products");
XElement refXElement = xdoc.XPathSelectElement("body/par/child [@xml:id = '2']");
XElement newXElement = new XElement("span", retmodule.ToString());
refXElement.AddAfterSelf(newXElement);
xdoc.Save();
关于c# - 使用 LINQ 交换元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10938448/