[英]How to write CData of XML which contain inner nodes in C#?
我有以下xml文件
<Node id="1" name="name1" autoplayTrailer="false" visible="true" bgimages="false">
<Text>
<title id="2" type="text" hideineditor="false" visible="true"><![CDATA[Link]]></title>
<sections id="3" default="consideration">
<songs id="4" type="text" hideineditor="false" enabled="true" visible="true">
<![CDATA[
<div class="ThumbContainer">
Some text here
</div>
]]>
<songsTitle><![CDATA[sometexthtml here]]></songsTitle>
</songs>
</sections>
</Text>
</Node>
我想一一读取content/node
并修改CDATA
内容并将xml写入光盘。
问题是我无法为<songs>
节点编写 CData 因为它在<songTitle>
节点内有另一个节点而不关闭</song>
节点是否可以用 CData 编写节点,在 CData 内容之后有另一个节点?
试试 xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
foreach (XElement node in doc.Descendants("Node"))
{
XElement songs = node.Descendants("songs").FirstOrDefault();
XCData child = (XCData)songs.FirstNode;
string childStr = child.ToString();
childStr = childStr.Replace("Some text here", "Some text there");
child.ReplaceWith(childStr);
}
}
}
}
这是您要创建的输出吗?
此示例使用 XmlTextWriter API 在“歌曲”元素下输出 CData 和“其他元素”。
using System;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace WriteCData
{
class Program
{
static void Main(string[] args)
{
// some output to write to
XmlTextWriter xtw = new XmlTextWriter(@"c:\temp\CDataTest.xml", null);
// start at 'songs' element
xtw.WriteStartElement("songs");
xtw.WriteCData("<div class='ThumbContainer'>Some text here</div>");
xtw.WriteStartElement("songsTitle");
xtw.WriteCData("sometexthtml here");
xtw.WriteEndElement(); // end "songTitle"
xtw.WriteEndElement(); // end "songs"
xtw.Flush(); // clean up
xtw.Close();
}
}
}
输出:
<songs>
<![CDATA[<div class='ThumbContainer'>Some text here</div>]]>
<songsTitle><![CDATA[sometexthtml here]]></songsTitle>
</songs>
这个想法是用您从您在问题中提到的源文档中读取的值替换示例中使用的静态文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.