0

I have a string containing some 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?

2: How can I insert another XML string, HTML encoded into TheData? Example of the other 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?

4

1 回答 1

3

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

var doc = XDocument.Load(yourFilePath);

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

1:如何确保 XML 确实包含一个 TheData元素?

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

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

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

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

您不必在这里为 XML 编码而烦恼。XElement班级会照顾到这一点。

于 2013-07-25T17:05:17.223 回答