Thursday, March 29, 2007

How to remove empty elements from an XML document

Since this is kind of universally useful, I recently was able to perfect a little snippet of XSL to remove empty elements from an XML document. This only removes elements that have no inner content or attributes. (In case you're wondering, I did this to handle special legacy XML documents for serialization.)


<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="no" indent="no"/>
<xsl:strip-space elements="*" />
<xsl:template match="*[not(node()) and not(./@*)]"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>


And in case you're not familiar with how to apply XSL in .NET:

C#:

XmlDocument xsl = new XmlDocument();
xsl.LoadXml(XSL_REMOVE_EMPTY_NODES); // constant contains the XSL above

StringWriter writer = new StringWriter();
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(xsl);
transform.Transform(new XmlNodeReader(xml.doc), null, writer);
writer.Flush();

string transformedXml = writer.ToString();


VB.NET:

Dim xsl As XmlDocument = New XmlDocument()
xsl.LoadXml(XSL_REMOVE_EMPTY_NODES) ' constant contains the XSL above

Dim writer As StringWriter = New StringWriter()
Dim transform As XslCompiledTransform = New XslCompiledTransform()
transform.Load(xsl)
transform.Transform(New XmlNodeReader(xml.doc), Nothing, writer);
writer.Flush()

Dim transformedXml As String = writer.ToString()


You can also use a Stream or XmlWriter in place of a TextWriter like I have above. I just used a StringWriter since I needed a String for the final result.

Friday, March 23, 2007

"The project you are trying to open is a Web project. You need to open it by specifying its URL path."

I hate it when I get this error even when I am opening the project from a URL. Luckily, there's a simple solution.

In the same folder as the project file (.csproj or .vbproj) of the web project you are trying to open, make a new file with the same name as the project file with .webinfo tacked on the end.

Thus, if you have a project called MyWebProject.csproj, you create a new file called MyWebProject.csproj.webinfo. In that file, it needs a short XML snippet:


<VisualStudioUNCWeb>
<Web URLPath="http://localhost/MyWebProject/MyWebProject.csproj" />
</VisualStudioUNCWeb>


Obviously, you need to replace the URLPath value with the actual value for your web project file. Once you have this hint in place, Visual Studio should be able to load your web project without a hitch.

This seems to be Visual Studio .NET 2003 problem. I've not seen it manifest itself in Visual Studio .NET 2005 yet.