在C#中复制xml中的现有元素

时间:2014-06-30 15:09:12

标签: c# xml clone

请从这个xml中克隆元素 prijemkaItem

enter image description here

元素prijemkaItem由此函数获取:

XElement doc = XElement.Load("input.xml");            
        XmlReader reader = XmlReader.Create("input.xml");

        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:

                    if (reader.Name == "pri:prijemkaItem")
                        elementPrijemkaItem = XElement.ReadFrom(reader) as XElement;

                    break;
            }
        }
        reader.Close()

我想把这个元素放在自己身后。请知道,我该怎么做?

感谢您的任何建议。

1 个答案:

答案 0 :(得分:1)

为简单起见,假设您的Xml结构如下:

<?xml version="1.0" encoding="utf-8"?>
<dat:dataPack xmlns:dat="datNamespace">
  <dat:dataPackItem>
    <pri:prijemka xmlns:pri="priNamespace">
      <othernode></othernode>
    </pri:prijemka>
  </dat:dataPackItem>
</dat:dataPack>

如果要复制pri:prijemka节点,可以使用 Linq to Xml

//using System.Xml.Linq;

//load the xml file
Document doc = XDocument.Load( "D:\\input.xml" );
//get the "dat" namespace 
var datNamespace = doc.Root.GetNamespaceOfPrefix( "dat" );

//get "dat:dataPackItem" node
var dataPackItemNode = doc.Root.Element( datNamespace + "dataPackItem" );
//since you don't know the "pri" namespace you can do:
var prijemkaNode = dataPackItemNode.Descendants( )
                       .Where(x => x.Name.LocalName == "prijemka")
                       .FirstOrDefault();

//add it to the "dat:dataPackItem" node
dataPackItemNode.Add( prijemkaNode );
//save the xml file
doc.Save( "D:\\input.xml" );   

结果是:

<?xml version="1.0" encoding="utf-8"?>
<dat:dataPack xmlns:dat="datNamespace">
  <dat:dataPackItem>
    <pri:prijemka xmlns:pri="priNamespace">
      <othernode></othernode>
    </pri:prijemka>
    <pri:prijemka xmlns:pri="priNamespace">
      <othernode></othernode>
    </pri:prijemka>
  </dat:dataPackItem>
</dat:dataPack>