java - 如何动态返回每个节点的一组对象?

标签 java dom domparser

尊敬的所有尊贵成员(member)!!

我在使用 DOM 技术读取 xml 时遇到一些问题。我想为每个 xml 节点/元素获取一组对象。一组对象应包含如下内容:MyObject(String NodeName, String NodeValue, Map attributeMap)。用 DOM 可以做到这一点吗?任何建议表示赞赏。这是我的例子:

1/xml 文件:

<?xml version="1.0"?>
<company>
    <staff id="1001" adress="new york">
        <firstname>yong</firstname>
        <lastname>mook kim</lastname>
        <nickname>mkyong</nickname>
        <salary>100000</salary>
    </staff>
</company>

2/预期返回结果:

First set: 
   NodeName  = company
   NodeValue = null
   attributeMap = {null}
Second set: 
   NodeName  = staff
   NodeValue = null
   attributeMap = {id="1001",address="new york"}
Third Set:
   NodeName  = firstname
   NodeValue = yong
   attributeMap = {null}
Forth Set: 
   NodeName  = lastName
   NodeValue = mook kim
   attributeMap = {null}
And so on...

这是我的示例代码*

public ElementsContainer getElements(String filename) throws 
        ParserConfigurationException, SAXException, IOException{

    Node tempNode;
    NamedNodeMap nodeMapAttributes;
    Node node;
    Map<String, String> attributes = new HashMap<>();
    ElementsContainer elements = null;


    File file = new File(filename);
    DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = documentBuilder.parse(file);
    if(document.hasChildNodes()){
        for(int i=0; i<document.getChildNodes().getLength(); i++){
            tempNode = document.getChildNodes().item(i);
            if(tempNode.getNodeType() == Node.ELEMENT_NODE){
                if(tempNode.getNodeValue()==null){
                   if(tempNode.hasAttributes()){
                       nodeMapAttributes = tempNode.getAttributes();
                       for(int k=0; k<nodeMapAttributes.getLength(); k++){
                           node = nodeMapAttributes.item(k);
                           attributes.put(node.getNodeName(), node.getNodeValue());
                       }
                   }
                   else{
                       attributes.put("", "");
                   }
                   elements = new ElementsContainer(tempNode.getNodeName(),tempNode.getNodeValue(),attributes);
                }
                else{
                    if(tempNode.hasAttributes()){
                       nodeMapAttributes = tempNode.getAttributes();
                       for(int k=0; k<nodeMapAttributes.getLength(); k++){
                           node = nodeMapAttributes.item(k);
                           attributes.put(node.getNodeName(), node.getNodeValue());
                       }
                   }
                   else{
                       attributes.put("", "");
                   }
                   elements = new ElementsContainer(tempNode.getNodeName(),tempNode.getNodeValue(),attributes);
                }
            }
        }
    }
    return elements;
}

最佳答案

我很好奇为什么要采用与我在 your similar question 中提供的类似方法没有使用过。

尽管如此,您在当前方法中必须解决两个问题

  • 节点是嵌套的,单次传递是不够的
  • 捕获某种类型 Collection 中的每个节点 .
  • 作为要解决的第三个兴趣点,尽可能摆脱 if-else

一次方法是递归遍历Document:

private void processNodes(final NodeList list, 
                          final ElementContainer parent, 
                          final List<ElementContainer> elements){

  for(int i=0; i< list.getLength(); i++){
      final Node node = list.item(i);
       if("#text".equals(node.getNodeName())){
         parent.setValue(node.getNodeValue());
       }
       else{
         final ElementContainer p =  processNode(node, elements);
         processNodes(node.getChildNodes(), p, elements);
       }
  }
}

捕获每个节点:

private ElementContainer processNode(Node node, List<ElementContainer> elements){
  final ElementContainer element = new ElementContainer(node.getNodeName(), node.getNodeValue());

 if(node.hasAttributes()){
   final NamedNodeMap attrs = node.getAttributes();
   for(int k=0; k<attrs.getLength(); k++){
     final Node attr = attrs.item(k);
     element.addAttribute(attr.getNodeName(), attr.getNodeValue());
   }
  }
  elements.add(element);
  return element;
}

查看my example

关于java - 如何动态返回每个节点的一组对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24175736/

相关文章:

java - 有没有办法用 quarkus 处理与数据源的动态连接?

java - 使用 += 构建从 null 开始的字符串的紧凑方法

javascript - 使用 domparser 围绕代码块创建一个新的 div 容器

java - 在 Java 中读写 XML 文件的问题

javascript - 更健壮的 jQuery :hidden implementation

javascript - 如果 DOMParser innerHTML 是脚本,则不显示第一个元素

java - 如何给struts2标签添加CSS

java - java中两次的区别

javascript - 如何选择多个ID并检查其是否具有相同的文本?

html - 为什么这个简单的代码会使所有主要浏览器的浏览器标签崩溃?