如何在C#中编写包含内部节点的XML的CData?
我有以下xml文档如何在C#中编写包含内部节点的XML的CData?,c#,xml,xml-parsing,writexml,C#,Xml,Xml Parsing,Writexml,我有以下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> <sectio
<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>
这里有一些文字
]]>
我想逐一阅读内容/节点
,修改CDATA
内容,并将xml写入光盘
问题是我无法为
节点写入CData,因为它在
节点中有另一个节点,而不关闭
节点。是否可以在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在“songs”元素下输出CData和“other元素”
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();
}
}
}
使用系统;
使用系统文本;
使用System.Threading.Tasks;
使用System.Xml;
命名空间WriteCData
{
班级计划
{
静态void Main(字符串[]参数)
{
//一些要写入的输出
XmlTextWriter xtw=新的XmlTextWriter(@“c:\temp\CDataTest.xml”,null);
//从“歌曲”元素开始
xtw.书面声明(“歌曲”);
WriteCData(“此处的一些文本”);
xtw.WriteStarteElement(“songsTitle”);
WriteCData(“此处为sometexthtml”);
xtw.WriteEndElement();//结束“songTitle”
xtw.WriteEndElement();//结束“歌曲”
xtw.Flush();//清理
xtw.Close();
}
}
}
输出:
<songs>
<![CDATA[<div class='ThumbContainer'>Some text here</div>]]>
<songsTitle><![CDATA[sometexthtml here]]></songsTitle>
</songs>
这里有一些文字]]>
我们的想法是将示例中使用的静态文本替换为您在问题中提到的源文档中读取的值。您使用的是什么API?LINQ到XML?旧的
XmlDocument
<代码>XmlSerializer?使用XmlReader
直接读取(或者希望不使用)?XmlTextWriter编写元素..和StreamReader读取xmlstrings,这是您正在使用的非常低级的API。你能分享一个到目前为止你所拥有的代码的最简单的例子吗?你在哪里被卡住了?另一方面,只要可以将整个XML加载到内存中,使用LINQtoXML可能会更容易。