2008-08-19 154 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>");