[英]Extract and Modify cdata section of xml using c#
I have the following xml 我有以下xml
<parent>
<child>abra</child>
<child>kadabra</child>
<child>alakazam</child>
<![CDATA[ some data here ]]>
</parent>
I want to extract the cdata section, what I have done is - converted the data into string and extracted it with the following code 我想提取cdata部分,我所做的是 - 将数据转换为字符串并使用以下代码将其解压缩
string toText = xmlDoc.OuterXml.Substring(xmlDoc.OuterXml.IndexOf("<![CDATA[") + "<![CDATA[".Length);
toText = toText.Remove(toText.IndexOf("]]>"));
where xmlDoc is XMLDocument which contails above xml 其中xmlDoc是XMLDocument,它包含xml以上
Is there any better way of doing this? 有没有更好的方法呢?
I googled a lot, but what I got is extraction of cdata section only if its the only child of its parent element. 我google了很多,但我得到的是cdata部分的提取,只要它是其父元素的唯一子元素。
Finally I want to modify cdata section and modify the current xml as 最后我想修改cdata部分并修改当前的xml为
<parent>
<child>abra</child>
<child>kadabra</child>
<child>alakazam</child>
<![CDATA[ modified data here ]]>
</parent>
Given this valid XML sample : 鉴于这个有效的 XML示例:
<parent>
<child>1</child>
<child>2</child>
<child>3</child>
<![CDATA[ some data here ]]>
</parent>
Since the only text node that is direct child of <parent>
is the cdata section you want to get, you can do this way to select the cdata section and modify it's content : 由于<parent>
直接子节点唯一的文本节点是您想要获取的cdata节,因此您可以通过这种方式选择cdata节并修改其内容:
var cdata = (XmlCDataSection)xmlDoc.SelectSingleNode("/parent/text()");
cdata.InnerText = " modified data here ";
Console.WriteLine(xmlDoc.OuterXml);
Another possible approach is using XDocument
to replace the older library, XmlDocument
: 另一种可能的方法是使用XDocument
替换旧的库, XmlDocument
:
var doc = XDocument.Load("path_to_your_xml");
var xcdata = doc.DescendantNodes().OfType<XCData>().FirstOrDefault();
xcdata.Value = " modified data here ";
Console.WriteLine(doc.ToString());
The output is as follow (formatted for readability) : 输出如下(为便于阅读而格式化):
<parent>
<child>1</child>
<child>2</child>
<child>3</child>
<![CDATA[ modified data here ]]>
</parent>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.