简体   繁体   中英

How to read a value from embedded XML (xmlns) element in HTML Page using Javascript

Example code:

<div id="xmlData">
  <script id="data" type="application/xml">
    <xml>
      <s:Schema id="RowsetSchema" table="ARTICLE" xmlns:s="0" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:dt="1">
        <s:ElementType name="row" content="eltOnly">
          <s:AttributeType name="ID">
            <s:datatype dt:type="string" dt:maxLength="10" rs:maybenull="false" />
          </s:AttributeType>
          <s:AttributeType name="NAME">
            <s:datatype dt:type="string" dt:maxLength="30" />
          </s:AttributeType>
          <s:extends type="rs:rowbase" />
        </s:ElementType>
      </s:Schema>
      <rs:data xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema">
        <z:row ID="0001" NAME="name 1" />
        <z:row ID="0002" NAME="name 2" />
      </rs:data>
    </xml>
  </script>
</div>

This xml is embedded data in my html page. I need to read some values from this xml. How can I read the value in <s:Schema> for id or table in js?

I honestly didn't even know you could put XML in a script tag like this, but based on this question , you can do it like so, traversing the XML with selectors just like you would an HTML document:

 var xmlString = document.getElementById('data').innerText; var parser = new DOMParser(); var xmlDoc = parser.parseFromString(xmlString,"text/xml"); //can also use "application/xml" var xmlSchema = xmlDoc.querySelector("Schema"); var schemaId = xmlSchema.getAttribute("id"); console.log(schemaId); // "RowsetSchema" var schemaTable = xmlSchema.getAttribute("table"); console.log(schemaTable); // "ARTICLE"
 <div id="xmlData"> <script id="data" type="application/xml"> <xml> <s:Schema id="RowsetSchema" table="ARTICLE" xmlns:s="0" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:dt="1"> <s:ElementType name="row" content="eltOnly"> <s:AttributeType name="ID"> <s:datatype dt:type="string" dt:maxLength="10" rs:maybenull="false" /> </s:AttributeType> <s:AttributeType name="NAME"> <s:datatype dt:type="string" dt:maxLength="30" /> </s:AttributeType> <s:extends type="rs:rowbase" /> </s:ElementType> </s:Schema> <rs:data xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema"> <z:row ID="0001" NAME="name 1" /> <z:row ID="0002" NAME="name 2" /> </rs:data> </xml> </script> </div>

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