简体   繁体   English

将XElement插入另一个XElement的值

[英]Insert XElement into value of another XElement

I have an XDocument object which contains XHTML and I am looking to add ABBR elements into the string. 我有一个包含XHTML的XDocument对象,我想将ABBR元素添加到字符串中。 I have a List that I am looping through to look for values which need to be wrapped in ABBR elements. 我正在遍历一个List,以查找需要包装在ABBR元素中的值。

Lets say I have an XElement which contains XHTML like so: 可以说我有一个XElement,其中包含如下XHTML:

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

I need to adjust the value of the XElement to look like this: 我需要调整XElement的值,使其看起来像这样:

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

How do I do this? 我该怎么做呢?

UPDATE: 更新:

I am wrapping the value "will" with the HTML element ABBR. 我用HTML元素ABBR包装了“ will”值。

This is what I have so far: 这是我到目前为止的内容:

        // 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;
                    }
                }
            }
        }

The problem with this approach is that when I set the XElement Value property, it is encoding the XML tags (correctly treating it as a string rather than XML). 这种方法的问题在于,当我设置XElement Value属性时,它正在对XML标签进行编码(正确地将其视为字符串而不是XML)。

If innerText contains the right XML you can try the following: 如果innerText包含正确的XML,则可以尝试以下操作:

xhtmlElement.Value = XElement.Parse(innerText);

instead of 代替

xhtmlElement.Value = innerText;

you can : 您可以 :

  • change the element value first to string, 首先将元素值更改为字符串,
  • edit and replace the previous element with the xmltag, 编辑前一个元素并将其替换为xmltag,
  • and then replace old value with the new value. 然后将旧值替换为新值。

this might what you're looking for: 这可能是您想要的:

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));

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

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