字符串转义成XML字符串、XML

由网友(离心)分享简介:有没有C#的功能,可用于逃生和未逃脱一个字符串,它可以用来填补XML元素的内容?我使用VSTS 2008 + C#+ .NET 3.0。编辑1:我是串联简单和短期的XML文件,我不使用序列化,所以我需要显式地逃避手XML字符,例如,我需要把 A< b 到<富>< /富> ,所以我需要逃避字...

有没有C#的功能,可用于逃生和未逃脱一个字符串,它可以用来填补XML元素的内容?

我使用VSTS 2008 + C#+ .NET 3.0。

编辑1:我是串联简单和短期的XML文件,我不使用序列化,所以我需要显式地逃避手XML字符,例如,我需要把 A< b <富>< /富> ,所以我需要逃避字符串 A< b 并把它变成元素富。

解决方案

 公共静态字符串XmlEscape(字符串转义)
{
    XmlDocument的文档=新的XmlDocument();
    XmlNode的节点= doc.CreateElement(根);
    node.InnerText =转义;
    返回node.InnerXml;
}

公共静态字符串XmlUnescape(字符串转义)
{
    XmlDocument的文档=新的XmlDocument();
    XmlNode的节点= doc.CreateElement(根);
    node.InnerXml =逃脱;
    返回node.InnerText;
}
 

Is there any C# function which could be used to escape and un-escape a string, which could be used to fill in the content of an XML element?

XML

I am using VSTS 2008 + C# + .Net 3.0.

EDIT 1: I am concatenating simple and short XML file and I do not use serialization, so I need to explicitly escape XML character by hand, for example, I need to put a<b into <foo></foo>, so I need escape string a<b and put it into element foo.

解决方案

public static string XmlEscape(string unescaped)
{
    XmlDocument doc = new XmlDocument();
    XmlNode node = doc.CreateElement("root");
    node.InnerText = unescaped;
    return node.InnerXml;
}

public static string XmlUnescape(string escaped)
{
    XmlDocument doc = new XmlDocument();
    XmlNode node = doc.CreateElement("root");
    node.InnerXml = escaped;
    return node.InnerText;
}

阅读全文

相关推荐

最新文章