我怎样才能获得第一级的物品?

时间:2016-12-15 11:38:17

标签: javascript xml

所以,我有这个xml

<conversation>
    <question>
        <title>I want to get this parent</title>
        <question>
            <title>I don´t want to get this one</title>
        </question>
        <question>
            <title>I don´t want to get this one</title>
        </question>
    </question>

    <question>and get this one</question>
    <question>and also this one too</question>
</conversation>

我希望得到最高级别,直接从<conversation>降序而不是从任何其他标记下降......我怎样才能获得那3个<question>个节点?

5 个答案:

答案 0 :(得分:7)

document.querySelectorAll('conversation > question')

&gt;指直接孩子。

example here只是没有混淆:

console.log( 
	document.querySelectorAll('conversation > question')
)
<conversation>
  <question>
    <title>I want to get this parent</title>
    <question>
      <title>I don´t want to get this one</title>
    </question>
    <question>
      <title>I don´t want to get this one</title>
    </question>
  </question>

  <question>and get this one</question>
  <question>and also this one too</question>
</conversation>

答案 1 :(得分:1)

如果您想要的只是顶级<question>元素,那么@rlemonanswer就是您需要的元素。

如果你想要这些元素的文字,你需要稍微扩展他的代码:

console.log(
  Array.prototype.slice.call(                            // Convert the `querySelectorAll` result to an array
    document.querySelectorAll('conversation > question') // Get all top question nodes
  ).map(e => e.innerText || e.children[0].textContent)   // Get the element's text, or the element's first child's text.
) 
<conversation>
  <question>
    <title>I want to get this parent</title>
    <question>
      <title>I don´t want to get this one</title>
    </question>
    <question>
      <title>I don´t want to get this one</title>
    </question>
  </question>

  <question>and get this one</question>
  <question>and also this one too</question>
</conversation>

答案 2 :(得分:0)

我不确定这是否是您需要的,但是您放了javascript标签。 所以这里有一个JavaScript代码,它将为您提供所有节点:

document.getElementsByTagName('question');

答案 3 :(得分:0)

尝试这样做以获得第一级会话的孩子

document.getElementsByTagName('conversation')[0].children

答案 4 :(得分:0)

您可以将document.querySelectorAll()与选择器"conversation question"Array.from()一起使用,检查当前元素.parentElement.nodeName是否为"QUESTION",如果为true则返回空字符串,否则检查是否元素有.firstElementChild.firstElementChild.nodeName"TITLE",如果为true,则返回.firstElementChild.textContent,否则为.firstChild.textContent,在结果文本上调用.trim(),链{{1以.filter()作为参数来删除空字符串。

&#13;
&#13;
Boolean
&#13;
var questions =  Array.from(
  document.querySelectorAll("conversation question")
  , function(el) {
    return (el.parentElement.nodeName === "QUESTION"
            ? "" 
            : el.firstElementChild 
              && el.firstElementChild.nodeName === "TITLE"
                ? el.firstElementChild.textContent
                : el.firstChild.textContent).trim();
  }).filter(Boolean);

console.log(questions);
&#13;
&#13;
&#13;