我有一个包含XHTML的XDocument对象,我希望将ABBR元素添加到字符串中。我有一个List,我正在循环查找需要包含在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)。
答案 0 :(得分:0)
如果innerText包含正确的XML,您可以尝试以下操作:
xhtmlElement.Value = XElement.Parse(innerText);
而不是
xhtmlElement.Value = innerText;
答案 1 :(得分:0)
这可能是您正在寻找的:
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));