【问题标题】:Merge multiple xml files into one using linq to xml使用 linq to xml 将多个 xml 文件合并为一个
【发布时间】:2013-09-10 10:43:56
【问题描述】:

说,这是我的 XML 文件

XML 文件 1

<Root>
    <Parent>
        <Child>1</Child>
        <child>2</Child>
    </Parent>
    <Parent>
         <child>3</Child>
         <Child>4</Child>
    </Parent>
 </Root>

Xml 文件 2

<Root>
    <Parent>
       <Child>5</Child>
       <Child>6</Child>
    </Parent>
    <Parent>
        <Child>7</Child>
        <Child>8</Child>
    </Parent>
 </Root>

生成的 XML 文件(根据我的要求)

<Root>
    <Parent>
       <Child>1</Child>
       <Child>2</Child>
    </Parent>
    <Parent>
        <Child>3</Child>
        <Child>4</Child>
    </Parent>
    <Parent>
       <Child>5</Child>
       <Child>6</Child>
    </Parent>
    <Parent>
        <Child>7</Child>
        <Child>8</Child>
    </Parent>

 </Root>

在下面的函数中,我提供了 xml 文件的路径以组合在一个字符串数组中并尝试合并它们

private void BindDataInGrid(string[] argFilePaths)
{
    XDocument tempFile = XDocument.Load(argFilePaths[0]);

    for (int i = 1; i < argFilePaths.Length; i++)
    {
        tempFile.Descendants("Parent")
           .Union(XDocument.Load(argFilePaths[i]).Root.Descendants("Parent"));
    }
 }

在 tempFile 中,只有第一个文件的记录,其他文件没有。

【问题讨论】:

标签: c# xml linq


【解决方案1】:

首先,很抱歉,我忘了提及我不想永久保存生成的文件。我自己解决了。

private void BindDataInGrid(string[] argFilePaths)
{
    List<Parent> recordsList = new List<Parent>();

        for (int i = 0; i < argFilePaths.Length; i++)
        {
           recordsList.AddRange
               (
                     XDocument.Load(argFilePaths[i]).Root.Descendants("Resident")
                     .Select(data => new Parent()
                     {
                         Child1 = data.Element("Child1").Value,
                         Child2 = data.Element("Child2").Value,
                     }).ToList()
                );
        }
}

使用 recordsList 作为数据源。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 2021-05-28
    • 2012-09-03
    • 2013-12-20
    • 2011-06-23
    相关资源
    最近更新 更多