简体   繁体   English

XElement.Parse和属性中的特殊字符

[英]XElement.Parse and special characters in attribute

I have a string containing xml eg: 我有一个包含xml的字符串,例如:

<Person Name="Molly O&apos;Mahony" />

I want to convert this to an XElement, maintaining the & apos ; 我想将其转换为XElement并保持& apos ; and not converting it to ' 而不是将其转换为“

using 使用

XElement.Parse(string);

creates the element <Person Name="Molly O'Mahony" /> Is this possible? 创建元素<Person Name="Molly O'Mahony" />这可能吗?

Here we go: 开始了:

var txt = "<Person Name=\"Molly O&apos;Mahony\" />";

var e  = XElement.Parse(txt, LoadOptions.SetLineInfo);
var li = (IXmlLineInfo) e.Attribute("Name");

// li.LinePosition points to first char of the attribute: Name="Molly O&apos;Mahony"
//                                                        ^

var start = txt.IndexOf('"', li.LinePosition) + 1;  
var end   = txt.IndexOf('"', start);
var len   = end - start;

var attr  = txt.Substring(start, len); // Molly O&apos;Mahony

You might need to adjust the code to make it work with multi-line text. 您可能需要调整代码以使其与多行文本一起使用。

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

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