如何根据 Xdocument 中的同级值在新元素内划分同级元素?
How can I divide sibling elements inside new elements based on a sibling value in Xdocument?
我有这些条目元素:
<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");
我有这些条目元素:
<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");