转义XML标签内容
我有一个简单的CAML查询,例如
<Where><Eq><Field="FieldName"><Value Type="Text">Value text</Value></Field></Eq></Where>
我有一个变量来代替"值文本"。验证/转义.NET框架中此处替换的文本的最佳方法是什么?
我已经对这个问题进行了快速的网络搜索,但是我发现的只是System.Xml.Convert
类,但这似乎并不是我在这里所需要的。
我知道我可以在这里使用XmlWriter
,但是对于这样一个简单的任务,似乎需要很多代码,我只需要确保Value text
部分的格式正确即可。
解决方案
回答
使用System.Xml.Linq.XElement
和SetValue
方法。这将设置文本的格式(假定为字符串),但也允许我们将xml设置为值。
回答
我不确定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回答的那样。这也需要C3.0,而且我不确定我们要定位的是哪个.Net Framework。如果目标不是.Net 3.5,并且想操纵Xml,建议我们仅将Xpath与C#一起使用。该参考文献详细介绍了如何将xpath与C一起使用来操作xml,而不是我一概而论。
回答
我们可以使用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"; }
回答
使用XML时,请始终使用与编程环境一起使用的XML API。不要尝试构建自己的XML文档构建和转义代码。正如Longhorn213所提到的,.Net中所有合适的东西都位于System.XML命名空间中。尝试编写自己的代码来编写XML文档只会导致许多错误和麻烦。
回答
在我的案例中,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>";
回答
用这个:
System.Security.SecurityElement.Escape("<unescaped text>");