c# - 修改文本 XmlNode 的 InnerXml

标签 c# xml-parsing xmldocument sgmlreader

我使用 SGML 和 XmlDocument 遍历一个 html 文档。当我找到一个类型为文本的 XmlNode 时,我需要更改其具有 xml 元素的值。我无法更改 InnerXml,因为它是只读的。我尝试更改 InnerText,但这次标记描述符字符 <>编码为 &lt;&gt; .例如:

<p>
    This is a text that will be highlighted.
    <anothertag />
    <......>
</p>

我正在尝试更改为:

<p>
    This is a text that will be <span class="highlighted">highlighted</span>.
    <anothertag />
    <......>
</p>

修改文本 XmlNode 值的最简单方法是什么?

最佳答案

我有一个解决方法,我不知道它是一个真正的解决方案还是什么,但它可以产生我想要的结果。请评论此代码是否值得解决

    private void traverse(ref XmlNode node)
    {
        XmlNode prevOldElement = null;
        XmlNode prevNewElement = null;
        var element = node.FirstChild;
        do
        {
            if (prevNewElement != null && prevOldElement != null)
            {
                prevOldElement.ParentNode.ReplaceChild(prevNewElement, prevOldElement);
                prevNewElement = null;
                prevOldElement = null;
            }
            if (element.NodeType == XmlNodeType.Text)
            {
                var el = doc.CreateElement("text");
                //Here is manuplation of the InnerXml.
                el.InnerXml = element.Value.Replace(a_search_term, "<b>" + a_search_term + "</b>");
                //I don't replace element right now, because element.NextSibling will be null.
                //So I replace the new element after getting the next sibling.
                prevNewElement = el;
                prevOldElement = element;
            }
            else if (element.HasChildNodes)
                traverse(ref element);
        }
        while ((element = element.NextSibling) != null);
        if (prevNewElement != null && prevOldElement != null)
        {
            prevOldElement.ParentNode.ReplaceChild(prevNewElement, prevOldElement);
        }

    }

此外,我删除了 <text></text>遍历函数后的字符串:

        doc = new XmlDocument();
        doc.PreserveWhitespace = true;
        doc.XmlResolver = null;
        doc.Load(sgmlReader);
        var html = doc.FirstChild;
        traverse(ref html);
        textBox1.Text = doc.OuterXml.Replace("<text>", String.Empty).Replace("</text>", String.Empty);

关于c# - 修改文本 XmlNode 的 InnerXml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7902515/

相关文章:

c# - 用于选择特定节点下的节点(中间有零个或多个节点)的 XPath

c# - API 选择,我应该返回 XPathNavigator 还是 XmlDocument

c# - 过滤 IEnumerable 模式

c# - 显示 PDF - 应用程序页面 SharePoint

java - DocumentBuilder.parse() -- 权限被拒绝

c# - 使用 C# 按 Alpha.Numeric 对 XML 节点进行排序

c# - 在具有相同属性的 XML 元素之间导航

c# - 使用 SharpDX : How to Draw over the screen surface? 的 HUD 基础知识

c# - 从文件中检索数据并存储在变量c#中

xml - 需要用 xmlpath/xmlsearch 提取数据