如何根据 Xdocument 中的同级值将同级元素划分到新元素中
本文关键字:元素 划分 新元素 何根 Xdocument | 更新日期: 2023-09-27 18:37:15
我有这些条目元素:
<Entry>
<pos STYLE="NUM">1</pos >
<tran></tran>
<pos STYLE="NUM">2</pos >
<example></example>
<pos STYLE="NUM">3</pos >
<elem></elem>
</Entry>
<Entry>
...
</Entry>
如何将 num 元素之间的元素转换为新元素,所以最后我有这个:
<Entry>
<body>
<tran></tran>
</body>
<body>
<example></example>
</body>
<body>
<elem></elem>
</body>
</Entry>
编辑::到目前为止,我加载xml文档迭代所有元素并执行一些与此问题无关的格式
XDocument doc = XDocument.Load(sourceDocument,LoadOptions.PreserveWhitespace);
foreach (XElement rootElement in doc.Root.Elements())
{
foreach (XElement childElement in rootElement.Descendants())
{
//add new body if <pos style=num>
if (childElement.Attribute("STYLE") != null)
{
//if next node is NUM
var nextNode = childElement.XPathSelectElement("following-sibling::*");
if (nextNode != null)
if (nextNode.Attribute("STYLE").Value == "NUM")
{
newBodyElem = new XElement("body");
}
}
}
它可以被视为一个分组问题,它重组了条目元素的内容:
XDocument doc = XDocument.Load("input.xml");
foreach (XElement entry in doc.Descendants("Entry").ToList())
{
foreach (var group in entry.Elements().Except(entry.Elements("pos")).GroupBy(child => child.ElementsBeforeSelf("pos").Last()))
{
group.Remove();
group.Key.ReplaceWith(new XElement("body", group));
}
}
doc.Save("output.xml");