简体   繁体   English

替换XML中的混合内容(纯文本+标记)

[英]Replace mixed content in XML (plain text + tags)

The program takes an xml that is mixture between html and custom tags. 该程序采用的xml是html和自定义标记之间的混合。 I want to replace this custom tag: 我要替换此自定义标签:

<replaceable />

With this: 有了这个:

Some text
<div>Other text</div>

The main problem is that any framework or library that I can use to properly handle XML (like LinqToXML or System.Xml) cannot get the whole content. 主要问题是,我可以用来正确处理XML的任何框架或库(如LinqToXML或System.Xml)都无法获取全部内容。 If try like this: 如果这样尝试:

// replaceable is an XElement for <replaceable />
// content is a string
replaceable.ReplaceWith(content)

It ends up all as escaped text, and is taken as the value for the XElement. 它最终全部作为转义文本,并作为XElement的值。

And if I try the XElement.Parse() method, like other questions here suggest, I lose the plain text at the beginning, and only the <div> remains. 而且,如果我尝试XElement.Parse()方法(如此处的其他问题所示),则会在开始时丢失纯文本,仅保留<div>

Is there a way to do this kind of replacement without going all regex on it? 有没有办法在不进行所有正则表达式的情况下进行这种替换?

You need to wrap the content in a tag before you parse it, so that XElement.Parse() can give you all of the nodes. 您需要在解析内容之前将其包装在标记中,以便XElement.Parse()可以为您提供所有节点。

var outer = XElement.Parse("<dummy>" + content + "</dummy>");
replaceable.ReplaceWith(outer.Nodes());

Using a string you are replacing the element with a text node. 使用字符串将元素替换为文本节点。 You want to first create an new XElement and use it for replacement. 您要首先创建一个新的XElement并将其用于替换。

replaceable.ReplaceWith(new XElement("div", otherText));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM