【问题标题】:Escaping XML tag contents转义 XML 标记内容
【发布时间】:2010-09-06 05:39:01
【问题描述】:
我有一个简单的 CAML 查询,例如
<Where><Eq><Field="FieldName"><Value Type="Text">Value text</Value></Field></Eq></Where>
我有一个变量可以代替Value text。验证/转义在 .NET 框架中替换的文本的最佳方法是什么?
我已经对这个问题进行了快速的网络搜索,但我发现的只是System.Xml.Convert 类,但这似乎不是我需要的。
我知道我可以在这里使用XmlWriter,但对于这样一个简单的任务,我只需要确保Value text 部分的格式正确,似乎有很多代码。
【问题讨论】:
标签:
.net
xml
frameworks
escaping
encode
【解决方案1】:
使用System.Xml.Linq.XElement 和SetValue 方法。这将格式化文本(假设为字符串),但也允许您将 xml 设置为值。
【解决方案2】:
使用这个:
System.Security.SecurityElement.Escape("<unescaped text>");
【解决方案3】:
您可以使用 System.XML 命名空间来执行此操作。当然你也可以使用 LINQ。但我选择了 .NET 2.0 方法,因为我不确定您使用的是哪个版本的 .NET。
XmlDocument doc = new XmlDocument();
// Create the Where Node
XmlNode whereNode = doc.CreateNode(XmlNodeType.Element, "Where", string.Empty);
XmlNode eqNode = doc.CreateNode(XmlNodeType.Element, "Eq", string.Empty);
XmlNode fieldNode = doc.CreateNode(XmlNodeType.Element, "Field", string.Empty);
XmlAttribute newAttribute = doc.CreateAttribute("FieldName");
newAttribute.InnerText = "Name";
fieldNode.Attributes.Append(newAttribute);
XmlNode valueNode = doc.CreateNode(XmlNodeType.Element, "Value", string.Empty);
XmlAttribute valueAtt = doc.CreateAttribute("Type");
valueAtt.InnerText = "Text";
valueNode.Attributes.Append(valueAtt);
// Can set the text of the Node to anything.
valueNode.InnerText = "Value Text";
// Or you can use
//valueNode.InnerXml = "<aValid>SomeStuff</aValid>";
// Create the document
fieldNode.AppendChild(valueNode);
eqNode.AppendChild(fieldNode);
whereNode.AppendChild(eqNode);
doc.AppendChild(whereNode);
// Or you can use XQuery to Find the node and then change it
// Find the Where Node
XmlNode foundWhereNode = doc.SelectSingleNode("Where/Eq/Field/Value");
if (foundWhereNode != null)
{
// Now you can set the Value
foundWhereNode.InnerText = "Some Value Text";
}
【解决方案4】:
就我而言,System.Xml 方法的问题在于构建这个简单的 XML 片段需要太多代码。我想我找到了妥协。
XmlDocument doc = new XmlDocument();
doc.InnerXml = @"<Where><Eq><Field Name=""FieldName""><Value Type=""Text"">/Value></Field></Eq></Where>";
XmlNode valueNode = doc.SelectSingleNode("Where/Eq/Field/Value");
valueNode.InnerText = @"Text <>!$% value>";
【解决方案5】:
使用 XML 时,请始终使用适用于您的编程环境的 XML API。不要尝试滚动您自己的 XML 文档构建和转义代码。正如 Longhorn213 所提到的,在 .Net 中,所有适当的东西都在 System.XML 命名空间中。尝试编写自己的代码来编写 XML 文档只会导致许多错误和麻烦。
【解决方案6】:
我不确定 xml 来自什么上下文,但如果它存储在您创建的字符串 const 变量中,那么修改它的最简单方法是:
public class Example
{
private const string CAMLQUERY = "<Where><Eq><Field=\"FieldName\"><Value Type=\"Text\">{0}</Value></Field></Eq></Where>";
public string PrepareCamlQuery(string textValue)
{
return String.Format(CAMLQUERY, textValue);
}
}
当然,这是基于问题的最简单的方法。您还可以将 xml 存储在 xml 文件中,然后读取并以这种方式操作它,就像 Darren Kopp 回答的那样。这也需要 C# 3.0,我不确定您的目标是什么 .Net Framework。如果您的目标不是 .Net 3.5 并且想要操作 Xml,我建议您只使用带有 C# 的 Xpath。这个reference 详细介绍了使用 xpath 和 C# 来操作 xml,而不是我全部输入。