Xml
Xslt
To debug in Visual Studio 2005, use the XslCompiledTransform(true) constructor.
XslCompiledTransform transformer = new XslCompiledTransform();
transformer.Load("transform.xslt");
XsltArgumentList args = new XsltArgumentList();
args.AddParam("ID", "", "Value"); //second argument is namespace
transformer.Transform("data.xml", args, Response.OutputStream);
Formatted XmlDocument
private static string FormattedXml(XmlNode doc) //quickly format xml string
{
MemoryStream ms = new MemoryStream(); //could use stringbuilder but always utf16
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true; //in 1.1 an xmlTextwriter with Formatting= Formatting.Indented
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(ms, settings))
{
doc.WriteTo(writer);
}
return Encoding.UTF8.GetString(ms.ToArray());
}
AddElement
Everybody writes a version of this when using XmlDocument. Makes it easy to chain together too.
private static XmlElement AddElement(XmlNode parent, string name)
{
XmlElement element = parent.OwnerDocument.CreateElement(name);
parent.AppendChild(element);
return element;
}
XPath in XDocument
XPath is often more readable for complex parsing. The extension requires "using System.Xml.XPath;"
//using System.Xml.Linq;
var webConfig = XDocument.Load(fileName);
//using System.Xml.XPath;
XElement e = webConfig.XPathSelectElement("configuration/system.web/httpModules/add[@name='AuthModule']");
XHTML
Doesn't work if the page uses html entities ( ) and non-closing tags (look out for <script />), but otherwise this is okay.
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true; //if saving
doc.XmlResolver = null; //we don't want to resolve the w3c DTD
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("html", "http://www.w3.org/1999/xhtml");
To use entities, create a custom XmlResolver
SQL Server 2005
FOR XML returns Xml Fragments (no root node- append , root('rootName')
).
Rename columns with aliases (and tables for xml auto).
SQLServer | Clause | Result | |
---|---|---|---|
2000+ | For Xml Raw[('ElementName')] |
<row NAME="RED"/> <ElementName NAME="RED"/> with for xml Raw('ElementName') |
|
2000+ | For Xml Auto [,Elements] |
<TABLENAME NAME="RED"/> NB joined tables are nested |
<TABLENAME> <NAME>RED<NAME> </TABLENAME> |
2005+ | For Xml Path |
Easy elements/attributes and nesting- use xpath in aliasselect '1' as '@id', 'New York' as 'address/city/@value'
|
XQuery: For the SQL2005 xml data type, use xmlColumn.query('/xpath')
in the sql.
Where xmlColumn.exists('/root/possiblenode')=1
Namespaces: xmlColumn.query(declare namespace a='uri'; /a:element)
Xml contsriuction (with curly braces): xmlColumn.query('<NewRoot> { /OldRoot } </NewRoot>')
There's a for-loop constructxmlColumn.query('{ for $n in /root/a
return string($n)
}')
There's even xml DML: xmlDolumn.modify('replace value of (/root/a)[1] with "New Text")