I have a SharePoint 2010 solution with a custom web part. I am using C# in Visual Studio 2012. The user has selected a view from a list, which I am storing as an SPView object, mobjView. I want to replace the < OrderBy > portion with new code, but preserve the < Where > portion, so my question involves the best way to parse the CAML string. This is what I have, I couldn't get Regex to cooperate, so I am wondering if there is a simpler way to parse the string (Where clause shortened to '...' for clarity).

// old string "<OrderBy><FieldRef Name='Title' /></OrderBy><Where>...</Where>" 
string strQuery = mobjView.Query.Substring(mobjView.Query.IndexOf("<Where>"))
strQuery = "<OrderBy><FieldRef Name='MyField' /></OrderBy>" + strQuery;
// new string  "<OrderBy><FieldRef Name='MyField' /></OrderBy><Where>...</Where>" 

1 Answer 1


You could use the XmlReader class: https://msdn.microsoft.com/en-us/library/system.xml.xmlreader%28v=vs.95%29.aspx

or the XmlDocument class (my preference): https://msdn.microsoft.com/en-us/library/system.xml.xmldocument.loadxml%28v=vs.110%29.aspx

You'd do something like:

XmlDocument doc = new XmlDocument();
XmlNodeList nodelist = doc.SelectNodes("OrderBy"); 

foreach (XmlNode node in nodelist) // nodelist should only contain the single OrderBy clause
    node.InnerXml = "<FieldRef Name='MyField' />";
mobjView.Query = doc.OuterXml;
  • Thanks, but that's a lot more complicated than a string substitution.
    – CigarDoug
    Jan 27, 2016 at 18:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.