简体   繁体   中英

$.parseXML() is not working with xml string without root node

Below is my code

 var str = "<single><n>Q1</n><v></v><m></m></single>
            <single><n>Q2</n><v>y</v><m></m></single>
            <single><n>Q3</n><v></v><m>y</m></single>";  
 // ! I gave this string value in three lines just for readability purpose

 var xmlDoc = $.parseXML( str );

 var xml = $(xmlDoc);

 alert(xml.find('single').size());  

But this is not working, Please check this fiddle

Look in the browser's error console: You will see something like

uncaught invalid xml

Adding a root element will fix it:

 <data>
 <single><n>Q1</n><v></v><m></m></single>
 <single><n>Q2</n><v>y</v><m></m></single>
 <single><n>Q3</n><v></v><m>y</m></single>
 </data>

Check this fiddle: http://jsfiddle.net/GeWZP/4/

You are missing your ROOT node. A XML does need a Root node and from that ROOT node you can generate child nodes.

var str = "<root>
               <single><n>Q1</n><v></v><m></m></single>
               <single><n>Q2</n><v>y</v><m></m></single>
               <single><n>Q3</n><v></v><m>y</m></single>
           </root>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM