简体   繁体   English

html中的xml可以从javascript / jquery中读取

[英]xml in html to be read it from javascript/jquery

I have an html file like this: 我有一个这样的html文件:

<html>
    <script src="/path/to/script1.js"></script>
    <xml id = "PageXML">
        <books>
            <book>
                <name>b1</name>
                <name>b2</name>
            </book>
        </books>
    </xml>
</html>

My question is: in Script1.js, I am able to get the xml as a text ( $('#PageXML').text() ), but I want to read the xml tag content as xml only and load it into the xmldocument in jquery/javascript file. 我的问题是:在Script1.js中,我能够以文本( $('#PageXML').text() )的形式获取xml,但是我想将xml标记内容仅读取为xml并将其加载到jQuery / javascript文件中的xmldocument

Is it possible? 可能吗?

您可以使用$('#PageXML').html()获得:

<books><book><name>b1</name><name>b2</name></book></books>

You can read it as HTML and parse to XML object using jQuery.parseXML() . 您可以将其读取为HTML并使用jQuery.parseXML()解析为XML对象。 Then place it in any variable. 然后将其放在任何变量中。

 xmlString = $('#PageXML')[0].outerHTML; XMLParsed = jQuery.parseXML(xmlString); console.log(XMLParsed); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <xml id="PageXML"><books><book><name>b1</name><name>b2</name></book></books></xml> 

(i am not abler to comment yet) (我尚无法发表评论)

After reading your comment on Filipes Answer. 阅读您对Filipes Answer的评论后。 Try to add a valid xml-header before passing the string to your dom Parser. 在将字符串传递到dom解析器之前,尝试添加有效的xml标头。

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<books><book><name>b1</name><name>b2</name></book></books>

Which XML-Parser are you using? 您正在使用哪个XML解析器?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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