2

I am adding XmlElement to an existing document but an extra attribute is being added. Here is the code:

XmlNode manifest = this.getManifestNode ();
XmlElement manifestEntry = _content.CreateElement ("item", _contentPath);
XmlAttribute id = _content.CreateAttribute ("id"); 
id.Value = "content" + getManifestNodes ().Count;
XmlAttribute href = _content.CreateAttribute ("href"); 
href.Value = splitPath [splitPath.Length - 1]; 
XmlAttribute mediaType = _content.CreateAttribute ("media-type"); 
mediaType.Value = "application/xhtml+xml"; 
manifestEntry.Attributes.Append (id); 
manifestEntry.Attributes.Append (href); 
manifestEntry.Attributes.Append (mediaType); 
manifest.AppendChild (manifestEntry);

and the resulting XML:

<item id="content3" href="test1.html" media-type="application/xhtml+xml" xmlns="/home/jdphenix/epubtest/test/OEBPS/content.opf" />

Where is the

xmlns="/home/jdphenix/epubtest/test/OEBPS/content.opf"

coming from? The path that it adds is the location of the document on disk, but I'm not adding it in my code (atleast, that I am aware of). Let me know if you need to know more details.

Edit: I modified my code per Filburt's suggestion and changed

XmlElement manifestEntry = _content.CreateElement ("item", _contentPath);

to

XmlElement manifestEntry = _content.CreateElement ("item");

This is a step in the right direction, but produces the following XML:

<item id="content3" href="test1.html" media-type="application/xhtml+xml" xmlns="" />
jdphenix
  • 15,022
  • 3
  • 41
  • 74
  • My problem with the blank xmlns attribute is probably a duplicate of http://stackoverflow.com/questions/135000/how-to-prevent-blank-xmlns-attributes-in-output-from-nets-xmldocument, looking into it now – jdphenix Dec 09 '11 at 20:31
  • This happens because .NET's Xml classes treat xmlns properly. This "problem" was caused by my lack of understanding of XML namespaces. The output was producing a blank xmlns attribute entry because it was told to do so by the call to XmlElement manifestEntry = _content.CreateElement ("item"); instead of XmlElement manifestEntry = _content.CreateElement ("item", "http://www.idpf.org/2007/opf"); I did not provide details in my original question to properly answer. See http://stackoverflow.com/questions/135000/how-to-prevent-blank-xmlns-attributes-in-output-from-nets-xmldocument. – jdphenix Dec 09 '11 at 20:43

1 Answers1

2

You're adding this namespace yourself (Line 2):

XmlElement manifestEntry = _content.CreateElement ("item", _contentPath);

See XmlDocument.CreateElement Method (String, String) - the first String parameter is the qualified name of the element you are adding and the second string is the namespace.

Try

XmlElement manifestEntry = _content.CreateElement ("item");

and everything should be fine.

Filburt
  • 17,626
  • 12
  • 64
  • 115