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

时间:2018-02-02 08:05:12

标签: c# xml

这是一个简单的xml文档

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

我想在data

下的option元素下插入某些元素

这是我写的代码

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>

怎么做????

1 个答案:

答案 0 :(得分:0)

试试这个解决方案。我使用过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>