如何基于节点将一个 XML 文件拆分为多个 XML 文件 [英] How to Split an XML file into multiple XML Files based on nodes

查看:45
本文介绍了如何基于节点将一个 XML 文件拆分为多个 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的 XML 文件

I have an XML file as follows

<?xml version="1.0>
<EMR>
  <CustomTextBox>
    <Text>WNL</Text>
    <Type>TextBox</Type>
    <Width>500</Width>
    <id>txt1</id>
  </CustomTextBox>

  <CustomTextBox>
    <Text>WNL</Text>
    <Type>TextBox</Type>
    <Width>500</Width>
    <id>txt2</id>
  </CustomTextBox>

  <AllControlsCount>
    <Width>0</Width>
    <id>ControlsID</id>
  </AllControlsCount>
</EMR>

我想将 xml 文件拆分为三个.根据其节点

I want to split the xml file int o three. According to its nodes

文件 1:

<?xml version="1.0>
<CustomTextBox>
  <Text>WNL</Text>
  <Type>TextBox</Type>
  <Width>500</Width>
  <id>txt1</id>
</CustomTextBox>

文件 2:

<?xml version="1.0>
<CustomTextBox>
  <Text>WNL</Text>
  <Type>TextBox</Type>
  <Width>500</Width>
  <id>txt2</id>
</CustomTextBox>

文件 3:

<?xml version="1.0>
<AllControlsCount>
  <Width>0</Width>
  <id>ControlsID</id>
</AllControlsCount>

而且节点是动态的,它们可能会改变.如何根据节点将这个 xml 文件拆分为多个.如果有人知道请分享.

Also the nodes are dynamic, they may change. How can I split this xml file as multiple according to the nodes. If anybody knows please share.

推荐答案

尝试 LinqToXml:

var xDoc = XDocument.Parse(Resource1.XMLFile1); // loading source xml
var xmls = xDoc.Root.Elements().ToArray(); // split into elements

for(int i = 0;i< xmls.Length;i++)
{
    // write each element into different file
    using (var file = File.CreateText(string.Format("xml{0}.xml", i + 1)))
    {
        file.Write(xmls[i].ToString());
    }
}

它将获取在根元素中定义的所有元素,并将其内容写入单独的文件中.

It will take all elements defined inside the root element and write its content into separate files.

这篇关于如何基于节点将一个 XML 文件拆分为多个 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆