CAR*_*TIC -2 javascript xml-parsing
我一直在尝试在java脚本中获取标签名称及其值。我使用的 xml 文件如下所示:
<root>
<note>
<to>Gil</to>
<from>
<firstname>john</firstname>
<lastname>corner</lastname>
</from>
<heading>Reminder</heading>
</note>
<note>
<to>Mary</to>
<from>
<firstname>Clara</firstname>
<lastname>Diana</lastname>
</from>
<heading>
How are you
</heading>
</note>
</root>
Run Code Online (Sandbox Code Playgroud)
我希望输出如下:
TageName : root Attribute: 0 Text: null
TageName : note Attribute: 0 Text: null
TageName : to Attribute: 0 Text: Gil
TageName : from Attribute: 0 Text: null
TageName : firstname Attribute: 0 Text: john
TageName : lastname Attribute: 0 Text: corner
TageName : heading Attribute: 0 Text: Reminder
TageName : note Attribute: 0 Text: null
TageName : to Attribute: 0 Text: Mary
TageName : from Attribute: 0 Text: null
TageName : firstname Attribute: 0 Text: Clara
TageName : lastname Attribute: 0 Text: Diana
TageName : heading Attribute: 0 Text: How are you
Run Code Online (Sandbox Code Playgroud)
这可能吗。如果是这样,请帮助我...
var xml = \'<root><note ><to>Gil</to><from><firstname>john</firstname><lastname>corner</lastname></from><heading>Reminder</heading></note><note><to>Mary</to><from><firstname>Clara</firstname><lastname>Diana</lastname></from><heading>How are you</heading></note></root>\';\n\nvar node = (new DOMParser()).parseFromString(xml, "text/xml").documentElement;\n\nvar nodes = node.querySelectorAll("*");\n\nfor (var i = 0; i < nodes.length; i++) {\n var text = null;\n if (nodes[i].childNodes.length == 1 && nodes[i].childNodes[0].nodeType == 3) //if nodeType == text node\n text = nodes[i].textContent; //get text of the node\n console.log("TageName : ", nodes[i].tagName, ", Text : ", text);\n}\xe2\x80\x8b\nRun Code Online (Sandbox Code Playgroud)\n