-1

I have this XML:

<Walls>                        <!-- Added by edit -->
  <Wall Height="1.0">
     <Corner X="15" Y="9"/>
     <Corner X="23.5" Y="9"/>
     <Corner X="23.5" Y="8.5"/>
     <Corner X="15" Y="8.5"/>
  </Wall>
  <Wall Height="3.0">
     <Corner X="14" Y="5.5"/>
     <Corner X="24" Y="5.5"/>
     <Corner X="24" Y="5"/>
     <Corner X="14" Y="5"/>
  </Wall> 
</Walls>                       <!-- Added by edit -->

And I made a parser for this in JavaScript:

if (window.DOMParser){
     var parser = new DOMParser();
     var doc = parser.parseFromString(stringContainingXMLSource, "application/xml");
     var xmlDoc = parser.parseFromString(txt, "application/xml");
}         
document.getElementById("Wall").innerHTML= xmlDoc.getElementsByTagName("Wall")[0].childNodes[1].nodeValue;

Now I want to have all the data from the XML, but in this way I cannot get it.
What did I do wrong?

zx485
  • 28,498
  • 28
  • 50
  • 59
  • 1
    Welcome to SO! This XML isn't valid without a root node. Please update your question to show [runnable code that reproduces the error](https://stackoverflow.com/help/mcve). – ggorlen Nov 18 '18 at 00:07
  • Ok, sorry :( I'm really distracted! Thx –  Nov 18 '18 at 00:16
  • Two days passed and you still haven't fixed this issue? I did it for you, but it seems that you have abandoned this question... – zx485 Nov 20 '18 at 00:27

1 Answers1

1

What do you expect the nodeValue to be for an empty element node? The nodeValue property is intended for For text, comment and CDATA nodes, perhaps you want to read the attribute values?

To read the attribute values, use getAttribute, e.g.

var xml = '<Wall Height="1.0">' +
            '<Corner X="15" Y="9"/>' +
            '<Corner X="23.5" Y="9"/>' +
            '<Corner X="23.5" Y="8.5"/>' +
            '<Corner X="15" Y="8.5"/>' +
          '</Wall>';

if (window.DOMParser){
  var parser = new DOMParser();
  var xmlDoc = parser.parseFromString(xml, "application/xml");
}

if (xmlDoc) {
  var nodes = xmlDoc.querySelectorAll('Corner');
  var wall = document.querySelector('#Wall');
  var html = Array.from(nodes).map((node, i) =>
    `${node.tagName} ${i}: X=${node.getAttribute('X')}, Y=${node.getAttribute('Y')}`
  );
  wall.innerHTML = html.join('<br>');
}
<div id="Wall"></div>

PS. It helps greatly if you post your code as a runnable snippet.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • thx. But this solution don't see the second wall. You can help me to see this? –  Nov 18 '18 at 02:17
  • @Walt057—as ggorlen said, the XML is not a valid document. Wrap it in another element, anything will do, e.g. `parser.parseFromString(\`
    ${xml}<\/div>\`, "application/xml")`.
    – RobG Nov 18 '18 at 08:10