繁体   English   中英

将现有的xml添加到现有的xml文档中

[英]Adding existing xml to existing xml document

这是一个简单的xml文档

<parent>
<control> </control>
<option>
  <data>
  </data>
</option>
</parent>

我想在option下的data元素下插入某些元素

这是我写的代码

XDocument xml2 = new XDocument();
            xml2 = XDocument.Parse(xEvent); //containing the above xml

            foreach(var element in xml2.Descendants())
            {
                if(element.Name == "Options")
                {
                    foreach(var element2 in element.Descendants())
                    {
                        if(elment.Name == 'Data')
                        {
                           //what to put in here? I want to insert the already made xml document
                        }
                    }
                }
            }

这是我想要的最终xml

 <Data>
    <TemplateID>xxxxx</TemplateID>
    <CaptionOptions>
        <CaptionField>
             <Field>xxx</Field>
             <Text>xxx</Text>
        </CaptionField>
        <CaptionField>            //All these are already present in a string/xml doc
              <Field>xxxx</Field>
              <Text>""</Text>
         </CaptionField>
         </CaptionOptions>
    </Data>

该怎么办????

试试这个解决方案。 我已经使用XML to LINQ方法。

using System.Linq;
using System.Xml.Linq;
using static System.Console;

string xml = @"<parent>
                    <control></control>
                    <option>
                      <data>
                      </data>
                    </option>
                    </parent>";

            // First let us parse the xml string using XElement
            var parsedXML = XElement.Parse(xml);

            // Now get the element from the <option>  tag.
            var firstElement = parsedXML.Element("option").Descendants().First();
            firstElement.Add(new XElement("TemplateID", "xxxx"));
            firstElement.Add(new XElement("CaptionOptions"));

            // You will use for loop here
            //{ 
            //firstElement.Element("CaptionOptions").Descendants().First().Add(new XElement("CaptionField"));
            firstElement.Element("CaptionOptions").Add(new XElement("CaptionField",
                                                           new XElement("Field", "xxxx"),
                                                           new XElement("Text", "hello")
                                                      ));

            //}
            WriteLine(parsedXML.ToString());

最后的xml看起来像这样-

<parent>
  <control></control>
  <option>
    <data>
      <TemplateID>xxxx</TemplateID>
      <CaptionOptions>
        <CaptionField>
          <Field>xxxx</Field>
          <Text>hello</Text>
        </CaptionField>
      </CaptionOptions>
    </data>
  </option>
</parent>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM