Default namespace created when adding XML document

I tried to add the xml file to an existing file, everything works fine, but I have a problem with the default namespace when it is added.

This is the code I use to add:

XmlNode newChild = doc.CreateNode(XmlNodeType.Element, "image", ""); newChild.Attributes.Append(doc.CreateAttribute("name", filename)); XmlNode xmlElement = doc.CreateNode(XmlNodeType.Element, "width", null); xmlElement.InnerText = widthValue[1].TrimStart(); newChild.AppendChild(xmlElement); 

I get the output as shown below

 <image d2p1:name="" xmlns:d2p1="test.jpg"> <width>1024</width> </image> 

but I tried to add:

 <image name="test.jpg"> <width>1024</width> </image> 
+4
source share
3 answers

Like others, using LINQ to XML can be simpler in general.

But if you want to use XmlDocument to fix this problem, change the code to the following:

 var attribute = doc.CreateAttribute("name"); attribute.Value = filename; newChild.Attributes.Append(attribute); 

The problem with the code you have is that doc.CreateAttribute("foo", "bar") creates an attribute named foo in the namespace with URI bar . This is really not what you want.

+3
source

I don’t know if you can use it, but you can do it with Linq To Xml as follows:

 // NOTE: Requires `using System.Xml.Linq;` var newChild = new XElement("image"); newChild.Add(new XAttribute("name", filename)); doc.Add(newChild); XElement xmlElement = new XElement("width"); xmlElement.Value = widthValue[1].TrimStart(); newChild.Add(xmlElement); 
+1
source

Can you use LINQ to XML to manage the file?

 var xml = XDocument.Parse(@"<xml><image name=""first_image.jpg""><width>800</width></image></xml>"); xml.Root.Add(new XElement("image", new XAttribute("name", "test.jpg"), new XElement("width", "1024"))); var result = xml.ToString(); 

The above code gives the following result:

 <xml> <image name="first_image.jpg"> <width>800</width> </image> <image name="test.jpg"> <width>1024</width> </image> </xml> 

No unwanted namespace information.

+1
source

Source: https://habr.com/ru/post/1396093/


All Articles