Home > database >  Why do I have an extra attribute in my XML XElement?
Why do I have an extra attribute in my XML XElement?

Time:06-14

I am creating an XML file which starts like this:

 XNamespace xNamespace = "http://www.topografix.com/GPX/1/1";
        var trkseg = new XElement("trkseg");
        XElement GPX = new XElement(xNamespace   "gpx",
            new XAttribute("xmlns", xNamespace),
            new XAttribute("version", "1.0"),
            new XAttribute("creator", "quilkin.co.uk"),
            new XElement("trk",
                new XElement("name", RouteName()),
                trkseg
            )
        );

which produces the following:

<gpx creator="quilkin.co.uk" version="1.0" xmlns="http://www.topografix.com/GPX/1/1">
  <trk xmlns="">
    <name>Route Name</name>
    <trkseg/>
  </trk>
</gpx>

I'm puzled why the 'trk' element has an attribute 'xlmns'. The addition of this isn't a problem with most readers of GPX files, but one (very common one!) does not like it and refuses to load the file.

I could manipulate the text to remove the attribute, but why is it occuring?

CodePudding user response:

The xmlns attribute defines the namespace of the current and all descendent elements that do not have an explicit namespace in front of them. Example:

<a xmlns="x">          // = namespace x, tag a
  <b>                  // = namespace x, tag b
    <c xmlns="">       // = empty namespace, tag c
      <d>              // = empty namespace, tag d
      </d>
    </c>
  </b>
</a>         

Or, if you prefer a more real-life example:

<html xmlns="http://www.w3.org/1999/xhtml">
  <body>
    <svg xmlns="http://www.w3.org/2000/svg">
      <rect x="20" y="20" width="50" height="50" />
    </svg>
  </body>
</html>

Here, html and body are in the XHTML namepsace, whereas svg and rect are in the SVG namespace.


In your code, you create gpx with the namespace contained in xNamespace, but you create subsequent elements with an empty namespace. Thus, XML needs to "reset" the namespace to empty in trk.

If you want to get rid of the xmslns="" attribute, just make sure that all elements are in the same namespace, i.e. replace

new XElement("trk",
    new XElement("name", RouteName()),
    new XElement("trkseg"))

with

new XElement(xNamespace   "trk",
    new XElement(xNamespace   "name", RouteName()),
    new XElement(xNamespace   "trkseg"))
  • Related