I have a file: A.xml containing something like this:
<?xml version="1.0"?>
<headernode>
</headernode>
Inside of the headernode i need to be able to dynamically load the contents of another xml file called B.xml containing the following
<?xml version="1.0"?>
<token>
<a>0</a>
</token>
My question is how do i get the contents of B.xml inside the header node of a.xml?
Thanks!
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
- load the DOM of A.xml
- locate the headernode
- load B.xml into DOM
- resolve the root of DOM for B
- copy root from DOM B
- put it as child to the located headernode of DOM A
- 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>
*/
来源:https://stackoverflow.com/questions/5810486/xml-how-to-read-one-file-into-another