从XML模板更新XML文件

时间:2013-07-19 19:31:23

标签: c# c++ xml

我有两个xml文件,一个名为config.xml和configtemplate.xml。我想要做的是从configtemplate.xml添加行到config.xml文件。

config.xml
<?xml version="1.0" encoding="utf-8"?>
<config>
 <Database>
    <DataType>1</DataType>
    <ServerName>192.168.50.80</ServerName>
  // add information here supplied by the configtemplate.xml
 </Database>

 <Services>
    <Wash>1</Wash>
  // add information here supplied by the configtemplate.xml
 </Services>

 <Options>
    <TaxRate>8.125</TaxRate>
    <AskForZipcode>0</AskForZipcode>
 // add information here supplied by the configtemplate.xml
 </Options>

我需要的是从configtemplate.xml获取所有数据并将其添加到配置文件中,而不会覆盖它们中的值。

同样,configtemplate.xml中的值将与它们可能具有的值不同。

configtemplate.xml
<?xml version="1.0" encoding="utf-8"?>
<config>
 <Database>
    <DataType>1</DataType>
    <ServerName>192.168.50.80</ServerName>
  // add all lines below to config.xml
    <DatabaseName>TestDB</DatabaseName>
 </Database>

 <Services>
    <Wash>1</Wash>
  // add all lines below to config.xmlxml
    <Greeter>0</Greeter>
 </Services>

 <Options>
    <TaxRate>8.125</TaxRate>
    <AskForZipcode>0</AskForZipcode>
 // add all lines below to config.xml
    <AutoSave>1</AutoSave>
 </Options>

我希望我能正确地解释并感谢你

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您可以使用ImportNode将数据从一个xml添加到另一个xml。

像这样。

XmlDocument doc1 = new XmlDocument();
doc1.Load("config.xml");
XmlDocument doc2 = new XmlDocument();
doc2.Load("configtemplate.xml");
XmlNode doc1root, doc2root, importNode;

doc1root = doc1.DocumentElement;
doc2root = doc2.DocumentElement;

foreach(XmlNode node in doc2root.ChildNodes)
{
    importNode = doc1root.OwnerDocument.ImportNode(node, true);
    doc1root.AppendChild(importNode);
}

这样,它会将{strong> configtemplate.xml 中的<Database><Services><Options>导入{{1}下的 config.xml }}

在您的情况下,您需要知道要从中导入和导出的标记,这在您的示例中未指定。

<强>解释

<config> config.xml 的根标记,即doc1root

<config> configtemplate.xml 的根标记,即doc2root

<config>循环中,您循环遍历foreach的每个子节点(doc2root<Database><Services>),并添加每个子节点都是<Options>

的子节点

使用上面的代码,您将得到一个新的 config.xml ,如下所示。

doc1root

顺便说一句,在xml中正确评论的方式与html相同,即<config> <Database> <DataType>1</DataType> <ServerName>192.168.50.80</ServerName> // add information here supplied by the configtemplate.xml </Database> <Services> <Wash>1</Wash> // add information here supplied by the configtemplate.xml </Services> <Options> <TaxRate>8.125</TaxRate> <AskForZipcode>0</AskForZipcode> // add information here supplied by the configtemplate.xml </Options> //below are from configtemplate.xml <Database> <DataType>1</DataType> <ServerName>192.168.50.80</ServerName> // add all lines below to config.xml <DatabaseName>TestDB</DatabaseName> </Database> <Services> <Wash>1</Wash> // add all lines below to config.xmlxml <Greeter>0</Greeter> </Services> <Options> <TaxRate>8.125</TaxRate> <AskForZipcode>0</AskForZipcode> // add all lines below to config.xml <AutoSave>1</AutoSave> </Options> </config>