0

我有两个 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>

我希望我能正确地自我解释,谢谢

4

1 回答 1

0

如果我对您的理解正确,您可以使用ImportNode将数据从一个 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);
}

这样它将<Database>, <Services>,<Options>configtemplate.xml导入到config.xml<config>

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

解释:

doc1rootconfig.xml的根标签,即<config>

doc2rootconfigtemplate.xml的根标签,即<config>

foreach循环中,您将遍历doc2root(分别为<Database><Services><Options>)的每个子节点,并将每个子节点添加为doc1root

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

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

顺便说一句,在xml中注释的正确方式和html是一样的,也就是<!--comment-->

于 2013-07-19T19:36:35.490 回答