【问题标题】:Insert XElement into value of another XElement将 XElement 插入另一个 XElement 的值
【发布时间】:2015-05-16 01:38:06
【问题描述】:

我有一个包含 XHTML 的 XDocument 对象,我希望将 ABBR 元素添加到字符串中。我有一个列表,我正在循环查找需要包装在 ABBR 元素中的值。

假设我有一个包含 XHTML 的 XElement,如下所示:

<p>Some text will go here</p>

我需要将 XElement 的值调整为如下所示:

<p>Some text <abbr title="Will Description">will</abbr> go here</p>

我该怎么做?

更新:

我用 HTML 元素 ABBR 包装值“will”。

这是我目前所拥有的:

        // Loop through them
        foreach (XElement xhtmlElement in allElements)
        {
            // Don't process this element if it has child elements as they
            // will also be processed through here.
            if (!xhtmlElement.Elements().Any())
            {
                string innerText = GetInnerText(xhtmlElement);

                foreach (var abbrItem in AbbreviationItems)
                {
                    if (innerText.ToLower().Contains(abbrItem.Description.ToLower()))
                    {
                        var abbrElement = new XElement("abbr", 
                            new XAttribute("title", abbrItem.Abbreviation),
                            abbrItem.Description);

                        innerText = Regex.Replace(innerText, abbrItem.Description, abbrElement.ToString(),
                                                  RegexOptions.IgnoreCase);

                        xhtmlElement.Value = innerText;
                    }
                }
            }
        }

这种方法的问题在于,当我设置 XElement Value 属性时,它正在对 XML 标记进行编码(正确地将其视为字符串而不是 XML)。

【问题讨论】:

  • 这里没有足够的信息。为什么要包裹“意志”?到目前为止,您尝试过什么?
  • 您对保留单词之间的确切空格等有多关心?
  • 这个问题有几个部分: (1) 给定一个字符串,找出其中已知的缩写。 (2) 给定一个缩写,找到它的描述。 (3) 给定一个包含文本的 XElement,用 XElement 替换部分文本。您在哪一部分需要帮助?
  • @Michael Liu,请看第 3 部分。

标签: c# xelement


【解决方案1】:

你可以:

  • 先将元素值改为字符串,
  • 编辑并用 xmltag 替换前一个元素,
  • 然后用新值替换旧值。

这可能是您正在寻找的:

var element = new XElement("div");
var xml = "<p>Some text will go here</p>";
element.Add(XElement.Parse(xml));

//Element to replace/rewrite
XElement p = element.Element("p");
var value = p.ToString();
var newValue = value.Replace("will", "<abbr title='Will Description'>will</abbr>");
p.ReplaceWith(XElement.Parse(newValue));

【讨论】:

    【解决方案2】:

    如果 innerText 包含正确的 XML,您可以尝试以下操作:

    xhtmlElement.Value = XElement.Parse(innerText);
    

    而不是

    xhtmlElement.Value = innerText;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多