Groups | Blog | Home
all groups > dotnet xml > september 2004 >

dotnet xml : Bulk add prefix to XmlDocument


Victor Hadianto
9/27/2004 2:03:02 AM
Hi All,

I have an XML document that looks like this:

<book>
<title>Foo</title>
<description>
<div xmlns="http://www.w3.org/1999/xhtml">
<p>Body this is the body</p>
</div>
</description>
</book>

Now I need to append this document into another XmlDocument object. To
correctly do this I want to add a namespace on the original XmlDocument with
"book" as it prefix. But I don't want change the namespace of the <div> since
it has a namespace defined on it.

So for example the result should look something like this:

<book:book xmlns:book="http://localhost/book.xsd">
<book:title>Foo</book:title>
<book:description>
<div xmlns="http://www.w3.org/1999/xhtml">
<p>Body this is the body</p>
</div>
</book:description>
</book:book>

So how would I do this? What's the best way to achive the result? I've tried
using Regex but soon stumped on the problem that it couldn't differentiate
non-namespaced nodes with the one with namespace. Or maybe with super funky
Regex I could use that, but is there a nicer XML way of doing it?

Thanks,
--
Victor Hadianto
http://www.synop.com/Products/SauceReader/
Martin Honnen
9/27/2004 2:09:21 PM


[quoted text, click to view]


[quoted text, click to view]

You could use XSLT to do this:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"
xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns:book="http://example.com/2004/books">

<xsl:output method="xml" encoding="UTF-8" />

<xsl:template match="xhtml:* | /">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:template>

<xsl:template match="*[namespace-uri() = '']">
<xsl:element name="{concat('book:', local-name())}"
namespace="http://example.com/2004/books">
<xsl:apply-templates select="@* | node()" />
</xsl:element>
</xsl:template>

<xsl:template match="@* | text() | processing-instruction() | comment()">
<xsl:copy />
</xsl:template>

</xsl:stylesheet>

The XslTransform class allows you to run XSLT transformations.




--

Martin Honnen
AddThis Social Bookmark Button