【问题标题】:Compare previous XML attribute with current in Java将以前的 XML 属性与 Java 中的当前属性进行比较
【发布时间】:2016-12-09 19:05:51
【问题描述】:

我有这个 XML:

<note>
      <text style="italic">Lorem ipsum dolor sit amet</text>
      <text style="italic">consectetur adipisicing elit, </text>
      <text>sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</text>
      <text style="bold">Ut enim ad minim veniam, quis nostrud exercitation</text>
      <text>ullamco</text>
</note>

这是我的问题:

我想循环遍历xml并将属性与之前的属性进行比较,看看它们是否相同。如果它们相同,我什么也不想做。如果它们不相同,我想将属性的值(斜体、粗体等)保存到 ArrayList。

这是我的代码:

List<String> styles = new ArrayList<String>();
List<Node> textNodesXML = new ArrayList<Node>();
textNodesXML = xpath.getNodes("/note/text");

for (Node n : textNodesXML)
{
   Node attribute = n.getAttributes().getNamedItem("style");
   Node nextSibling = getTheNextSibling(n);
   Node siblingAttribute= nextSibling .getAttributes().getNamedItem("style");

   //Code is working up until here.

   if (attribut != null && siblingAttribute.getNodeValue() != attribute.getNodeName())
   {
       styles.add(attribute.getTextContent());
   }
}


public static Element getTheNextSibling(Node node)
   {
      Node sibling = node.getNextSibling();
      while (sibling != null)
      {
         if (sibling.getNodeType() == Node.ELEMENT_NODE)
         {
            return (Element) sibling;
         }
         sibling = sibling.getNextSibling();
      }
      return null;
   }

我希望它出现在我的 ArrayList 样式中:

italic
bold

非常感谢

【问题讨论】:

  • 更容易使用HashMap 进行检查。您想只检查前一个元素的属性还是检查之前发生的所有属性?
  • 只有前一个属性。如何使用 HashMap?
  • 如果有 4 个元素元素交替使用相同的属性会怎样?例如:斜体,什么都没有,斜体,什么都没有?您的比较会将 2 个斜体添加到 ArrayList。这是期望的行为吗?
  • 是的,这是期望的行为。只要没有连续两个,我想添加每个属性。示例:斜体、无、斜体、无、粗体、粗体、无、粗体将添加 2 个斜体和两个粗体。

标签: java xml dom


【解决方案1】:

只需将当前样式值与列表中的最后一个进行比较即可:

代替

styles.add(attribute.getTextContent());

if (styles.isEmpty() || !styles.get(styles.size() - 1).equals(attribute.getTextContent())) {
    styles.add(attribute.getTextContent());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多