【问题标题】:Adding a parent element to existing elements using XDocument, XMLDocument or XPath?使用 XDocument、XMLDocument 或 XPath 向现有元素添加父元素?
【发布时间】:2019-06-04 03:21:14
【问题描述】:

对于以下问题,XMLDocument 还是 XDoc 哪个 API 需要更少的代码?除了 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>

【问题讨论】:

  • 如果没有定义一些价值体系,“更好”对工程师来说毫无意义。也许你可以更具体,例如“在性能方面更好”或“在兼容性方面更好”。否则,答案纯属见仁见智。
  • @JohnWu :是的,将其更改为哪种方式会更短,忽略性能和要转换的大量内容。
  • @JohnWu :实际上使用 XPath 可能是一项微不足道的任务,比 XDoc 或 XMLDocument 方法需要的编程要少得多。
  • 就个人而言,我可能会反序列化列表,将其映射到不同的列表,然后对其进行序列化。这将产生最具可读性、可维护性的代码 IMO。但它可能不是最短的。
  • @JohnWu :如果它是直截了当的,我会坚持下去,一直在与错误作斗争,XML 不是我经常做的事情,而且很可能再过几年也不会再做,乐于接受简单直截了当的方法,仅适用于此问题或类似问题中的简单测试数据。

标签: c# .net xml


【解决方案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)
                }));
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    只是添加父节点

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 2019-07-07
      • 2011-03-15
      相关资源
      最近更新 更多