如何在XML中搜索特定属性以检索其他属性?

时间:2016-04-24 22:34:00

标签: javascript xml google-maps geolocation

实际上,我正在尝试使用Google Maps Javascript API,以便从我的数据库中生成特定标记,以便在自动填充表单中使用它。 我无法在Google地方信息中保存我的标记,因为它会有太多,并且它们并不真正适合所有人!但是,Google并不知道我的所有地方,因此无法对其进行地理编码。 我决定用我的标记生成一个XML文件;这是一个样本:

<?xml version="1.0"?>
<markers>
  <marker name="Pan Africa Market" address="1521 1st Ave, Seattle, WA" lat="47.608940" lng="-122.340141" type="restaurant"/>
  <marker name="Buddha Thai &amp; Bar" address="2222 2nd Ave, Seattle, WA" lat="47.613590" lng="-122.344391" type="bar"/>
  <marker name="The Melting Pot" address="14 Mercer St, Seattle, WA" lat="47.624561" lng="-122.356445" type="restaurant"/>
  <marker name="Ipanema Grill" address="1225 1st Ave, Seattle, WA" lat="47.606365" lng="-122.337654" type="restaurant"/>
  <marker name="Sake House" address="2230 1st Ave, Seattle, WA" lat="47.612823" lng="-122.345673" type="bar"/>
  <marker name="Crab Pot" address="1301 Alaskan Way, Seattle, WA" lat="47.605961" lng="-122.340363" type="restaurant"/>
  <marker name="Mama's Mexican Kitchen" address="2234 2nd Ave, Seattle, WA" lat="47.613976" lng="-122.345467" type="bar"/>
  <marker name="Wingdome" address="1416 E Olive Way, Seattle, WA" lat="47.617214" lng="-122.326584" type="bar"/>
  <marker name="Piroshky Piroshky" address="1908 Pike pl, Seattle, WA" lat="47.610126" lng="-122.342834" type="restaurant"/>
</markers>

如何使用JavaScript来检索特定名称属性的latlng属性?

1 个答案:

答案 0 :(得分:1)

您可以使用以下XPath表达式:

  • /markers/marker[@name='Crab Pot']/@lng

  • /markers/marker[@name='Crab Pot']/@lat

来自Chrome开发者工具的

$x("/markers/marker[@name='Crab Pot']/@lat")

或以编程方式在JavaScript中使用 Document.evaluate()

console.log( document.evaluate("/markers/marker[@name='Crab Pot']/@lat", 
             document, null, XPathResult.FIRST_ORDERED_NODE_TYPE,
             null).singleNodeValue );