使用XDocument,XMLDocument或XPath向现有元素添加父元素吗?

时间:2019-06-04 03:21:14

标签: c# .net xml

对于以下问题,哪个API需要较少的代码,XMLDocument或XDoc?除了XMLDocument,XDoc或XPath之外,还有其他方法更适合此任务吗? (忽略性能和文件大小很小)

尝试将某些元素变成显示在列表中的节点的子元素,例如(缩进并不重要,请忽略它)

<PersonList>
  <Person>
    <Name>Name1</Name>
    <LName>LName1</LName>
    <Phone>Phone</Phone>
  </Person>
  <Person>
    <Name>Name2</Name>
    <LName>LName2</LName>
    <Phone>Phone2</Phone>
  </Person>
  <Person>
    <Name>Name3</Name>
    <LName>LName3</LName>
    <Phone>Phone3</Phone>
  </Person>
</PersonList>

我正试图把它们变成这个

<PersonList>
  <Person>
    <PersonDetailsList>
      <Name>Name1</Name>
      <LName>LName1</LName>
      <Phone>Phone</Phone>
    </PersonDetailsList>
  </Person>
  <Person>
    <PersonDetailsList>
      <Name>Name2</Name>
      <LName>LName2</LName>
      <Phone>Phone2</Phone>
    </PersonDetailsList>
  </Person>
    <Person>
      <PersonDetailsList>
        <Name>Name3</Name>
        <LName>LName3</LName>
        <Phone>Phone3</Phone>
      </PersonDetailsList>
  </Person>
</PersonList>

2 个答案:

答案 0 :(得分:1)

Xml Linq表现很好:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication7
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            List<XElement> people = doc.Descendants("Person").ToList();
            foreach (XElement person in people)
            {
                var children = person.Nodes().ToList();
                person.ReplaceWith(new XElement("Person", new object[] {
                    new XElement("PersonDetailsList", children)
                }));
            }
        }
    }
}

答案 1 :(得分:1)

只需添加父节点

var doc = XDocument.Parse(xml);
var elems = doc.Descendants("Person");
foreach (XElement elem in elems)
{
    elem.ReplaceWith(new XElement("PersonDetailsList", elem));
}