XML: How to read one file into another

自古美人都是妖i 提交于 2019-12-02 03:01:45

This seems to work:

var header = XDocument.Load("a.xml");
var token = XElement.Load("b.xml");

var headerNode = header.Elements("headernode").First();
headerNode.Add(token);

Console.WriteLine(header.ToString()); 
/*
The above prints:

<headernode>
  <token>
    <a>0</a>
  </token>
</headernode>
*/

If you can use Linq to XML this would be relatively simple:

XDocument doc1 = XDocument.Load("a.xml");
XDocument doc2 = XDocument.Load("b.xml");

doc1.Element("headernode").Add(doc2.Root);

I prefer some of the other answers, but this was the first thing that came to mind:

var a = new XmlDocument();
a.Load("c:\\a.xml");
var b = new XmlDocument();
b.Load("c:\\b.xml");
var node = a.SelectSingleNode("/headernode");
node.AppendChild(a.ImportNode(b.SelectSingleNode("/token"), true));
a.Save("c:\\c.xml"); 

This XQuery:

declare function local:copy-append($element as element()) {
   if ($element instance of element(headernode))
   then
      element headernode {$element/@*,doc('B.xml')}
   else
      element {node-name($element)}
         {$element/@*,
          for $child in $element/node()
          return if ($child instance of element())
                 then local:copy-append($child)
                 else $child
         }
};
local:copy-append(/*)

Output:

<headernode>
    <token>
        <a>0</a>
    </token>
</headernode>

Well, I do not know the exact way to do it in C-Sharp, but basically wouldn't be the default approach to

  1. load the DOM of A.xml
  2. locate the headernode
  3. load B.xml into DOM
  4. resolve the root of DOM for B
  5. copy root from DOM B
  6. put it as child to the located headernode of DOM A
  7. rewrite modified DOM A to file or whereever you want ?

Since Im a Java Developer I am not very familiar with the C-Sharp XML API but basically I've seen XMLDocument and XDocument there. And when I'm not wrong XDocument is newer and simpler, but both should do it somehow.

Does this help?

//myXmlToInsert.xml
/*
<?xml version="1.0"?>
<root>
  <child1></child1>
  <child2></child2>
  <token>
      <a>0</a>
  </token>
</root>
*/

//code
XDocument xmlDoc = new XDocument();
xmlDoc.Declaration = new XDeclaration("1.0", "utf-8", "yes");
xmlDoc.Document.Add(new XElement("rootNode",new XElement("headerNode"), new XElement("bodyNode")));
XDocument xmlToInsert = XDocument.Load(@"c:\myXmlToInsert.xml");
XElement tokenNode = xmlToInsert.Root.Element("token");

xmlDoc.Root.Element("headerNode").Add(tokenNode);    

//Result 
/*
<?xml version="1.0"?>
<root>
  <headerNode>
    <token>
       <a>0</a>
    </token>
   </headerNode>
   <bodyNode>
   </bodyNode>
</root>
*/
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!