在c#中包含xml文件

时间:2016-02-17 11:33:10

标签: c# xml include append

这是我的问题,我有两个xml文件,我想在父文件中包含子文件,看看如下所示

父亲

<?xml version="1.0" encoding="UTF-8"?>
<topolino.doc name="topolino.doc" type="doc" path="C:\Users\" filename="topolino.doc">
    <child.xml type="xml" name="child.xml" path="C:\" filename="child.xml" />
</topolino.doc>

<?xml version="1.0" encoding="UTF-8"?>
<adeel.doc name="adeel.doc" type="doc" path="C:" filename="adeel.doc">
  <pippo.doc type="doc" name="pippo.doc" path="C:" filename="pippo.doc" />
</adeel.doc>

结果

<?xml version="1.0" encoding="UTF-8"?>
<topolino.doc name="topolino.doc" type="doc" path="C:\Users\" filename="topolino.doc">
   <adeel.doc name="adeel.doc" type="doc" path="C:" filename="adeel.doc">
   <pippo.doc type="doc" name="pippo.doc" path="C:" filename="pippo.doc" />
</adeel.doc>
</topolino.doc>

最好的方法是什么?

事先提起安迪

1 个答案:

答案 0 :(得分:0)

string strParent=@"<?xml version=""1.0"" encoding=""UTF-8""?> 
                            <topolino.doc name=""topolino.doc"" type=""doc"" path=""C:\Users\"" filename=""topolino.doc""> \
                                <child.xml type=""xml"" name=""child.xml"" path=""C:\"" filename=""child.xml"" />
                            </topolino.doc>";

        string strChild = @"<?xml version=""1.0"" encoding=""UTF-8""?>
                        <adeel.doc name=""adeel.doc"" type=""doc"" path=""C:"" filename=""adeel.doc"">
                          <pippo.doc type=""doc"" name=""pippo.doc"" path=""C:"" filename=""pippo.doc"" />
                        </adeel.doc>";
        XmlDocument docParent = new XmlDocument();
        docParent.LoadXml(strParent);
        XmlDocument docChild = new XmlDocument();
        docChild.LoadXml(strChild);
        //docParent.AppendChild(docChild.ChildNodes.Item(0));
        var n = docParent.ImportNode(docChild.SelectSingleNode("adeel.doc"), false);
        var n1 = docParent.ImportNode(docChild.ChildNodes[1].SelectSingleNode("pippo.doc"), true);
        docParent.DocumentElement.AppendChild(n);
        docParent.DocumentElement.AppendChild(n1);