当前位置: 动力学知识库 > 问答 > 编程问答 >

Duplicate existing element in xml in C#

问题描述:

Please I would like to clone element prijemkaItem from this xml:

The element prijemkaItem is got by this function:

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()

I would like to put this element behind itself. Please any idea, how can I do this?

Thanks for any advice.

网友答案:

Assuming for simplicity that your Xml structure is the following:

<?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>

If you want to duplicate the pri:prijemka node you can use 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" );   

The result is:

<?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>
分享给朋友:
您可能感兴趣的文章:
随机阅读: