2008-08-19 155 views
1

我有一个简单的CAML查询像逃逸XML标签内容

<Where><Eq><Field="FieldName"><Value Type="Text">Value text</Value></Field></Eq></Where> 

而且我有一个变量来代替Value text。验证/转义在.NET框架中取代的文本的最佳方法是什么? 我在这个问题上做了一个快速的网络搜索,但所有我发现的是System.Xml.Convert类,但这似乎不是我所需要的。

我知道我可以在这里使用XmlWriter,但对于这样一个简单任务,我只需要确保Value text部分格式良好就好像有很多代码。

回答

0

使用System.Xml.Linq.XElementSetValue方法。这将格式化文本(假设字符串为),但也允许您将xml设置为值。

+0

我与.NET 2.0 – axk 2008-09-16 10:05:10

0

我不知道XML是来自哪个方面,但如果它被保存在您创建一个字符串常量变量,那么最简单的方法来修改这将是:

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详细介绍了如何在C#中使用xpath来处理xml,而不是我全部输入。

0

您可以使用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"; 
} 
+0

工作好像很多的代码,这样的基本任务。 – axk 2008-09-16 10:06:34

1

当使用XML,始终使用XML API与您的编程环境中工作。不要试图推出自己的XML文档构建和转义代码。正如Longhorn213所提到的,在.NET中,所有适当的东西都在System.XML命名空间中。试图编写自己的代码来编写XML文档只会导致许多错误和麻烦。

1

在我的情况下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>"; 
1

使用此:

System.Security.SecurityElement.Escape("<unescaped text>");