简体   繁体   中英

add namespace to a xml document in C#

I have the following xml

<book>
   <chapter>this is a sample text</chapter>
</book>

and need to add a namespace to it to be like the one below

<ns0:book xmlns:ns0="http://mybookurl/sample">
   <chapter>this is a sample text</chapter>
</ns0:book>

I tried Greco suggestions but it does not work. Creating a specific XML document using namespaces in C#

would appreciate any help!

Thanks

You can do this by loading the Xml into an XmLDocument then finding each node that you want to add ns0 to and setting that XmlNodes's Prefix property to "ns0".

Something like this:

XmlDocument myDoc = new XmlDocument();
myDoc.LoadXml("my_file.xml");

foreach (XmlNode eachBook in myDoc.GetElementsByTagName("book")) {
    eachBook.Prefix = "ns0";
}

myDoc.Save("my_changed_file.xml");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM