Don wrote:
If I have a well-formed XML document in a string, what can I do to get a
namespace added to it? What class, properties, and methods can I use?
The simplest and the most effective way is to crate custom XmlReader
which exposes required namespace. Here is the simplest form:
public class NamespacedXmlReader : XmlTextReader
{
public NamespacedXmlReader(TextReader r) :
base(r) {}
public override string NamespaceURI
{
get
{
return NodeType == XmlNodeType.Element? "http://foo.com" : "";
}
}
public override string Prefix
{
get
{
return NodeType == XmlNodeType.Element? "foo" : "";
}
}
}
Then read XML via this reader:
string xml = @"<bar attr=""val"">baz</bar>";
XmlReader r = new NamespacedXmlReader(new StringReader(xml));
XmlDocument doc = new XmlDocument();
doc.Load(r);
doc.Save(Console.Out);
The result is
<foo:bar attr="val" xmlns:foo="http://foo.com">baz</foo:bar>
You can remove Prefix property override to get default namespace form:
<bar attr="val" xmlns="http://foo.com">baz</bar>
--
Oleg Tkachenko [XML MVP, MCP]
http://blog.tkachenko.com