替换所有现有xml文件的字符串?

时间:2013-10-18 08:12:58

标签: c# xml

我正在尝试用String替换现有的.xml扩展文件的内部文本。

为什么我这样做是:我想从.xml文件中读取图像。但是图像没有从.xml文件的现有文件夹中加载文件。我试了很多次来解决这个问题。只有可能的事情是放置图像文件目的地的硬路径。所以我开始尝试这个:

  1. 读取.xml文件的内部字符串 - Solved
  2. 获取xml路径的完整父级 - 已解决
  3. 在xml中读取文本并导出到字符串 - 已解决
  4. 从字符串中找到“<img src='”已存在的区域 - 已解决
  5. 将父路径放在现有区域之后 - 已解决
  6. 通过替换所有字符串 - 未解决的?
  7. 将字符串保存到现有.xml

    工作目的是“从XML文件显示图像”。所以请有人回答未解决的文章。 并且不建议我使用像Base64ToImage这样的方法。我只想这样走。希望我能在这里得到答案。

    现有XML: <helpRoot> <body Type="Section1"> <![CDATA[ <img src='Help1.png'/>
    <h3 style="color:#2B94EA;font-family:open sans;">Section1</h3></hr>
    <p style="color:#484848;font-family:open sans;">Text is shown</p> <h3 style="color:#3399FF;font-family:open sans;"> Image is not showing</h3></hr>
    ]]></body> <body Type="Section2"> <![CDATA[ <img src='Help2.png'/>
    <h3 style="color:#2B94EA;font-family:open sans;">Section2</h3></hr>
    <p style="color:#484848;font-family:open sans;">Text is shown</p> <h3 style="color:#3399FF;font-family:open sans;"> Image is not showing</h3></hr>
    ]]></body> ... </helpRoot>

    新的XML字符串: <helpRoot> <body Type="Section1"> <![CDATA[ <img src='D:/Project/Image/Help1.png'/>
    <h3 style="color:#2B94EA;font-family:open sans;">Section1</h3></hr>
    <p style="color:#484848;font-family:open sans;">Text has showing</p> <h3 style="color:#3399FF;font-family:open sans;"> Image is showing</h3></hr>
    ]]></body> <body Type="Section2"> <![CDATA[ <img src='D:/Project/Image/Help2.png'/>
    <h3 style="color:#2B94EA;font-family:open sans;">Section2</h3></hr>
    <p style="color:#484848;font-family:open sans;">Text has shown</p> <h3 style="color:#3399FF;font-family:open sans;"> Image is not showing</h3></hr>
    ]]></body> ... </helpRoot>

1 个答案:

答案 0 :(得分:0)

我使用XDocumentHTMLAgilityPack

var xml =
@"<base>
    <child><![CDATA[<img src=""/path"" />]]></child>
</base>";

var xDocument = XDocument.Parse(xml);

var xChild = xDocument.Descendants("child").First();

var cData = xChild.Nodes().OfType<XCData>().First();

var htmlDocument = new HtmlDocument();

htmlDocument.LoadHtml(cData.Value);

var imgNode = htmlDocument.DocumentNode.SelectSingleNode("img");

imgNode.Attributes["src"].Value = "/new/path";

using (var writer = new StringWriter())
{
    htmlDocument.Save(writer);
    cData.Value = writer.ToString();
}

xDocument现在包含:

<base>
  <child><![CDATA[<img src="/new/path">]]></child>
</base>
相关问题