拆分xml文件并保留父节点信息
无论如何,通过使用 LINQ、XmlDocument 等,我可以将一个大的 xml 文件分割成较小的块并保留所有父节点值
对于在原始文件中找到的每个单元节点,示例 XML
<Inventory>
<Dealer>
<ID>123</ID>
<Phone>1235551234</Phone>
<Units>
<Unit>
<Year>
<Make />
<Model />
</Unit>
<Unit>
<Year />
<Make />
<Model />
</Unit>
</Units>
</Dealer>
<Dealer>
<ID>124</ID>
<Phone>1235554321</Phone>
<Units>
<Unit>
<Year />
<Make />
<Model />
</Unit>
<Unit>
<Year />
<Make />
<Model />
</Unit>
</Units>
</Dealer>
</Inventory>
块应该如下所示
<Inventory>
<Dealer>
<ID>123</ID>
<Phone>1235551234</Phone>
<Units>
<Unit>
<Year>
<Make />
<Model />
</Unit>
</Units>
</Dealer>
</Inventory>
我应该澄清一个问题,我尝试以编程方式构建从“Unit”节点开始的块。不知道父元素中可能包含什么。
到目前为止,我的解决方案是,
XDocument document = XDocument.Load("sample.xml");
var units = document.Descendents("Unit").ToList();
foreach (XElement unit in units)
{
XElement parent = unit;
XElement child = parent;
while (null != parent.Parent)
{
parent = parent.Parent;
parent.Descendents(child.Name).Remove();
parent.Add(child);
child = parent;
}
}
这对于每个经销商节点中的第一个单元非常有效,该经销商的每个后续单元都会丢失任何父信息,并且该块仅包含单元节点。
Is there anyway, either by using LINQ, XmlDocument etc, that I can split a large xml file into smaller chucks and retain all the parent node values
Sample XML
<Inventory>
<Dealer>
<ID>123</ID>
<Phone>1235551234</Phone>
<Units>
<Unit>
<Year>
<Make />
<Model />
</Unit>
<Unit>
<Year />
<Make />
<Model />
</Unit>
</Units>
</Dealer>
<Dealer>
<ID>124</ID>
<Phone>1235554321</Phone>
<Units>
<Unit>
<Year />
<Make />
<Model />
</Unit>
<Unit>
<Year />
<Make />
<Model />
</Unit>
</Units>
</Dealer>
</Inventory>
Chunks should look like this for each Unit node found in the original
<Inventory>
<Dealer>
<ID>123</ID>
<Phone>1235551234</Phone>
<Units>
<Unit>
<Year>
<Make />
<Model />
</Unit>
</Units>
</Dealer>
</Inventory>
I should clarify one issue, I'm trying to programmaticly build the chunks starting with the "Unit" node. w/o having knowledge of what may be contained in the parent elements.
My solution so far is
XDocument document = XDocument.Load("sample.xml");
var units = document.Descendents("Unit").ToList();
foreach (XElement unit in units)
{
XElement parent = unit;
XElement child = parent;
while (null != parent.Parent)
{
parent = parent.Parent;
parent.Descendents(child.Name).Remove();
parent.Add(child);
child = parent;
}
}
This works great for the first unit in each dealer node, each subsequent unit for that dealer loses any parent information and the chunk only contains the Unit node.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 selectSingleNode 或 selectNodes 方法选择节点并将其从 xml 文档中删除。
Select a node(s) using selectSingleNode or selectNodes method and remove it from xml document.
您可以使用 LINQ to XML + LINQ to Objects 来完成此操作,为了清楚起见,我将解决方案分为三个部分:首先选择单个单元,然后选择突变,然后分块:
You can do this with LINQ to XML + LINQ to Objects, for clarity I've split the solution into three parts: first selecting the individual units, then the mutation, then the chunking: