Reputation: 19366
I know how I can create a new XML file, set the declaration, the name space and add new elements to the root. However, if I want to append elements to an existing file it is added xmlns as attribute of the new element:
<NewElement p3:id="1" idAux="A1" xmlns:p3="http://xyz.com/2006/bbb" xmlns="">
I try to use the loaded the namespace of the document, but that does not work.
How can I add new elements to an existing file and respect the format of the existing elements?
I am using linq to xml.
Thanks.
Upvotes: 0
Views: 452
Reputation: 4234
Try the following code:
// Assume 'el' is the new element that's created.
XElement el = new XElement("NewElement", new XAttribute("{p3}id", 1), new XAttribute("idAux", "A1"));
The above should create the following:
<NewElement p3:id="1" idAux="A1">
Note that the namespace p3
may be created on the document root element--I'm not sure about that. Also I know that with the old System.Xml API, if you didn't specify a default namespace for your document, then the XmlSerializer
would add the xsi
and xsd
namespaces automatically.
I know in the old Xml API, the correct way to specify a default namespace was to add a XmlNamespaceManager
-type property to your class (which is a container for an array of XmlQualifiedName
objects) and add a XmlQualifiedName
object as follows: new XmlQualifiedName(string.Empty, "urn:your-namespace-name")
. You probably need to do something similar for your document using XML-to-LINQ.
I have a SO post about that: XmlSerializer: remove unnecessary xsi and xsd namespaces. HTH.
Upvotes: 1