Posts Tagged ‘XML’
MSBuild XslTransformation Xslt Task example
Goal: Change the connection string of my application while running CodedUI tests. So my dev database is left alone.
Here I’ll post a simple “Hello World” setup to alter a xml to output something else. The xml and xslt example has been taken from w3schools.
When you download this file. It will contain a cmd. It loads up environment variables for msbuild and executes the build.proj.
The build.proj looks like this :
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- Xml & Xslt Examples have been taken from http://www.w3schools.com/xsl/ --> <Target Name="Build"> <XslTransformation XslInputPath="transform.xslt" XmlInputPaths="source.xml" OutputPaths="out.html" /> </Target> </Project>
The output is a html page, just as the w3schools demo.
Hope this is a good starting example for your needs.
msbuild xslt demo
Xml literals escaping
I am somewhat bias towards C#, but one can admire the xml literals in vb.net.
This is a language feature where you can just add xml to
Dim someXml As XElement = <foo>bla<bar active=”false”/></foo>
But how do you add characters that have some a meaning in xml, like “&” or “<“. Turns out you have two options:
Look up how you should escape it (& => & ) but the editor (vs2013) will show wavy underlines underneath the literal. It will compile do and work as expected.
Embed a literal string
Dim someXml As XElement = <foo>Ampersand <%= “&” %><bar active=”false”/></foo>
this uses a method to embed expressions in xml literals.
Sql Server XML Cheetsheet
Cheet sheet XML Features SQL Server
Pre-requirement: Knowledge of XPath
All the samples are based on this XML:
<MyBooks> <ListOwner>John Smith</ListOwner> <Book> <title published="1885">The Adventures of Huckleberry Finn</title> <author realName="Samuel Langhorne Clemens">Mark Twain</author> </Book> <Book> <title published="1894">Tom Sawyer Abroad</title> <author realName="Samuel Langhorne Clemens">Mark Twain</author> </Book> </MyBooks> |
Extract Values
select @xml.value(‘( /MyBooks/ListOwner )[1]’, ‘varchar(20)’);
Possible error:
error | fix |
---|---|
‘value()’ requires a singleton (or empty sequence), found operand of type | place the XPATH query between ‘()[1]’ |
Check if exists
select @xml.exist(‘ //Book[author/@realName=”Samuel Langhorne Clemens”] ‘)
select @xml.exist(‘ //Book[contains((author/@realName)[1],”Langhorne”)] ‘)
Extract Node
SELECT @xml.query(‘/MyBooks/Book’) –Results all book nodes.SELECT @xml.query(‘/MyBooks/Book[title=”The Adventures of Huckleberry Finn”]’)SELECT @xml.query(‘/MyBooks/Book[title/@published<1890]’)
Select nodes
This will allow you to run SQL queries on XML.
select t.c.value(‘(title)[1]’,’varchar(20)’) from @xml.nodes(‘ //Book ‘) as t(c)
Modify Xml
Namespaces:
When there are namespaces in you XML you will have to do additional work.