有没有办法使用jquery使用特定元素的值作为xml中的输入来查找同级元素值

Is there way to find sibling element values using a value of a particular element as input in xml using jquery

提问人:Venkatraj GM 提问时间:8/17/2023 最后编辑:Venkatraj GM 更新时间:8/17/2023 访问量:26

问:

在下面的例子中,我想使用值“Harry potter”作为jquery中的输入来找到作者,年份和价格的值

<bookstore>
     <book>
      <title>Everyday Italian</title>
      <author>Giada De Laurentiis</author>
      <year>2005</year>
      <price>30.00</price>
     </book>
     <book>
      <title>Harry Potter</title>
      <author>J K. Rowling</author>
      <year>2005</year>
      <price>29.99</price>
     </book>
    </bookstore>
jQuery ajax XML

答:

-1赞 jdweng 8/17/2023 #1

使用 Powershell

using assembly System.Xml.Linq

$filename = "c:\temp\test.xml"

$doc = [System.Xml.Linq.XDocument]::Load($filename)
$books = $doc.Descendants("book")

$table = [System.Collections.ArrayList]::new()
foreach($book in $books)
{
   $title = $book.Element('title').Value
   $author = $book.Element('author').Value
   $year = $book.Element('year').Value
   $price = $book.Element('price').Value
   $newRow = [pscustomobject]@{
      title=$title
      author=$author
      year=$year
      price=$price
   }
   $table.Add($newRow) | Out-Null
}
$table | Format-Table

结果

title            author              year price
-----            ------              ---- -----
Everyday Italian Giada De Laurentiis 2005 30.00
Harry Potter     J K. Rowling        2005 29.99

评论

1赞 epascarello 8/17/2023
不确定这个答案是否符合标签......
1赞 epascarello 8/17/2023 #2

有很多方法可以攻击它。简单的方法是使用jQuery将其转换为XML(如果您还没有该格式)。然后,您可以遍历它并找到标题并过滤与相同文本匹配的标题。之后,您可以拿到书并循环到孩子们身上以获得您想要的属性。

const xmlString = `
<bookstore>
  <book>
    <title>Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book>
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
</bookstore>
`;

// convert the xml into an object
const doc = $($.parseXML(xmlString));

// find all the titles that match
const titles = doc.find('book title').filter((_, title) => title.textContent === 'Harry Potter');

const data = titles.get().map((title) => {
  const book = $(title).parent();
  return book.children().get().reduce((obj, elem) => ({...obj, [elem.tagName]: elem.textContent}), {});
});

console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>