将XML插入XML元素

时间:2021-08-22 09:15:32

I have a string containing some XML:

我有一个包含一些XML的字符串:

<some>
  <xml></xml>
  <tags/>

  <TheData/>

  <more>asdf</more>
  <of/>
  <them></them>
</some>

Instead of <TheData/> we could have <TheData></TheData> or other equivalent forms.

我们可以使用 或其他等效形式代替

Questions:

问题:

1: How can I make sure that the XML does indeed contain an empty TheData element?

1:如何确保XML确实包含空的TheData元素?

2: How can I insert another XML string, HTML encoded into TheData? Example of the other XML:

2:如何插入另一个XML字符串,HTML编码到TheData中?其他XML的示例:

<mydata>
  <name>John</name>
  <address>New York City</address>
</mydata>

End result:

最终结果:

<some>
  <xml></xml>
  <tags/>

  <TheData>
    &lt;mydata&gt;
      &lt;name&gt;John&lt;/name&gt;
      &lt;address&gt;New York City&lt;/address&gt;
    &lt;/mydata&gt;
  </TheData>

  <more>asdf</more>
  <of/>
  <them></them>
</some>

Are there quick ways to do this with e.g. LINQ to XML?

有没有快速的方法来做到这一点,例如LINQ to XML?

1 个解决方案

#1


3  

First of all, you have to load your XML into memory as an XDocument instance:

首先,您必须将XML作为XDocument实例加载到内存中:

var doc = XDocument.Load(yourFilePath);

Then, you can answer your questions:

然后,您可以回答您的问题:

1: How can I make sure that the XML does indeed contain an empty TheData element?

1:如何确保XML确实包含空的TheData元素?

var theData = doc.Root.Element("TheData");

if(theData != null && string.IsNullOrEmpty((string)theData))
{
    // document contains TheData element which is empty
}

2: How can I insert another XML string, HTML encoded into TheData?

2:如何插入另一个XML字符串,HTML编码到TheData中?

theData.Value = @"<mydata>
                      <name>John</name>
                      <address>New York City</address>
                  </mydata>";

You don't have to bother about XML encoding here. XElement class will take care of that.

您不必在此处理解XML编码。 XElement类将负责这一点。

#1


3  

First of all, you have to load your XML into memory as an XDocument instance:

首先,您必须将XML作为XDocument实例加载到内存中:

var doc = XDocument.Load(yourFilePath);

Then, you can answer your questions:

然后,您可以回答您的问题:

1: How can I make sure that the XML does indeed contain an empty TheData element?

1:如何确保XML确实包含空的TheData元素?

var theData = doc.Root.Element("TheData");

if(theData != null && string.IsNullOrEmpty((string)theData))
{
    // document contains TheData element which is empty
}

2: How can I insert another XML string, HTML encoded into TheData?

2:如何插入另一个XML字符串,HTML编码到TheData中?

theData.Value = @"<mydata>
                      <name>John</name>
                      <address>New York City</address>
                  </mydata>";

You don't have to bother about XML encoding here. XElement class will take care of that.

您不必在此处理解XML编码。 XElement类将负责这一点。