如何在C#中基于匹配的XmlNode从层次结构克隆单个XML

问题描述

这是XML结构:

<root>
    <listofItems>
        <item>
            <lineItem>1</lineItem>
            <itemDetail>
                <partNum>A1</partNum>
                <color>red</color>
                <qty>4</qty>
            </itemDetail>
        </item>
        <item>
            <lineItem>2</lineItem>
            <itemDetail>
                <partNum>B2</partNum>
                <color>blue</color>
                <qty>2</qty>
            </itemDetail>
        </item>
        <item>
            <lineItem>3</lineItem>
            <itemDetail>
                <partNum>C3</partNum>
                <color>green</color>
                <qty>1</qty>
            </itemDetail>
        </item>
    </listofItems>
</root>

知道partNum是B2,我将如何克隆整个项目B2,所以我有2个相同的B2项目。

解决方法

您可以使用CloneNode函数复制节点,然后使用AppendChild将其附加到层次结构中的相关位置。

// find the node
var target = doc.SelectSingleNode("root/listOfItems/item/itemDetail/partNum[text()='B2']");

// clone
var clonedNode = target.ParentNode.CloneNode(true);

// attach
target.ParentNode.ParentNode.AppendChild(clonedNode);
,

这是System.Xml.Linq解决方案。

//Load the XML Document
XDocument xdoc = XDocument.Load(xDocPath);

//Find the XMLNode
XElement xB2 = xdoc.Root.Element("listOfItems").Elements("item").FirstOrDefault(it => it.Element("itemDetail").Element("partNum").Value.Equals("B2"));

//Clone the XMLNode
XElement xB2Copy = new XElement(xB2);

XElement xB2链接到xdoc。 XElement xB2Copy未链接到xdoc。

您必须首先添加它,下面是一些示例。

xdoc.Root.Element("listOfItems").Add(xB2Copy);

xB2.AddAfterSelf(xB2Copy);

xB2.AddBeforeSelf(xB2Copy);
,

尝试以下操作:

using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication166
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement listOfItems = doc.Descendants("listOfItems").FirstOrDefault();
            XElement itemB = listOfItems.Elements("item").Where(x =>  x.Descendants("partNum").Any(y => (string)y == "B2")).FirstOrDefault();

            listOfItems.Add(XElement.Parse(itemB.ToString()));
        }
    }
 
}