使用DOM解析器解析xml并添加限制

时间:2021-12-18 00:59:54

I am trying to use DOM parser for my xml.The code is as follows. It lists all the elements by tag type and its properties like price and color. However its hard time for me to find out how to add restrictions to the code such as "give me all the pens that are above $10" or "the name of pen whose color is black". Can someone help me out.

我正在尝试为我的xml使用DOM解析器。代码如下。它按标签类型及其属性(如价格和颜色)列出所有元素。然而,我很难找到如何为代码添加限制,例如“给我10美元以上的所有笔”或“颜色为黑色的笔的名称”。有人可以帮我吗。

Thanks
My .xml file looks something like this:

谢谢我的.xml文件看起来像这样:

 <equipment>
  <type>
   <description>pen</description>
   <name>parker</name>
   <price value="USD">8.00</price>
   <color>black</color>
 </type>
  <type>
   <description>pen</description>
   <name>ball point</name>
   <price value="USD">20.00</price>
   <color>purple</color>
 </type>
 <type>
   <description>pen</description>
   <name>sharpie</name>
   <price value="USD">15.00</price>
   <color>blue</color>
 </type>
 <type>
   <description>pen</description>
   <name>staples</name>
   <price value="USD">6.00</price>
   <color>red</color>
 </type>
 <type>
   <description>pen</description>
   <name>integra</name>
   <price value="USD">12.00</price>
   <color>white</color>
 </type>

Here is the code for my parser

这是我的解析器的代码

 public static void main(String[] args)throws SAXException, IOException,   ParserConfigurationException {

            File fXmlFile = new File("docs\\abc.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("type");
            for(int i=0;i<nList.getLength();i++){
                Node nNode = nList.item(i);

                    if(nNode.getNodeType() == Node.ELEMENT_NODE){

                        Element eElement = (Element) nNode;
                        System.out.println("Name:" + getTagValue("name", eElement));
                        System.out.println("Price: "+ getTagValue("price", eElement));
                        System.out.println(getAttributeValue("price", "value", eElement));
                        System.out.println("Description: "+getTagValue("description", eElement));
                        System.out.println("color:"+ getTagValue("color", eElement));
                    }
            }

        }

         private static String getTagValue(String sTag, Element eElement) {
            NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
            Node nValue = (Node) nlList.item(0);

            return nValue.getNodeValue();
         }

         private static String getAttributeValue(String sTag, String attributeName, Element eElement){
            NamedNodeMap nodeMap = eElement.getElementsByTagName(sTag).item(0).getAttributes();

            return nodeMap.getNamedItem(attributeName).getNodeValue();
         }
    }

2 个解决方案

#1


0  

If you want to parse XML based on some criteria, you can use the Java XPath API instead of DOM based parser.

如果要根据某些条件解析XML,可以使用Java XPath API而不是基于DOM的解析器。

#2


0  

If you wish to add filters you better do it manually and using XMLStreamReader might help.follow the steps:

如果您希望添加过滤器,最好手动执行,并使用XMLStreamReader可能会有所帮助。请按照以下步骤操作:

  1. Transform your XML file into a string using Transformer
  2. 使用Transformer将XML文件转换为字符串

  3. convert the String into a byte array and pass it to the XMLStreamReader.
  4. 将String转换为字节数组并将其传递给XMLStreamReader。

  5. Iterate from one element to another
  6. 从一个元素迭代到另一个元素


Transformer t=TransformerFactory.newInstance().newTransformer();
StringWriter sw=new StringWriter();         
StreamResult result=new StreamResult(sw);
DOMSource d=new DOMSource(XMLdoc);
t.transform(d, result);
tring xmlstring=sw.toString();

ByteArrayInputStream bain = new yteArrayInputStream(xmlstring.getBytes());
XMLInputFactory factory1 = XMLInputFactory.newInstance();
XMLStreamReader reader = factory1.createXMLStreamReader(bain);

while(reader.hasNext())
{
    reader.next();
    if(reader.getEventType==XMLStreamReader.START_ELEMENT)
    {
        if(reader.getLocalName().equals("price"))
        {
            //your logic
        }
    }
}

hope it helps..

希望能帮助到你..

#1


0  

If you want to parse XML based on some criteria, you can use the Java XPath API instead of DOM based parser.

如果要根据某些条件解析XML,可以使用Java XPath API而不是基于DOM的解析器。

#2


0  

If you wish to add filters you better do it manually and using XMLStreamReader might help.follow the steps:

如果您希望添加过滤器,最好手动执行,并使用XMLStreamReader可能会有所帮助。请按照以下步骤操作:

  1. Transform your XML file into a string using Transformer
  2. 使用Transformer将XML文件转换为字符串

  3. convert the String into a byte array and pass it to the XMLStreamReader.
  4. 将String转换为字节数组并将其传递给XMLStreamReader。

  5. Iterate from one element to another
  6. 从一个元素迭代到另一个元素


Transformer t=TransformerFactory.newInstance().newTransformer();
StringWriter sw=new StringWriter();         
StreamResult result=new StreamResult(sw);
DOMSource d=new DOMSource(XMLdoc);
t.transform(d, result);
tring xmlstring=sw.toString();

ByteArrayInputStream bain = new yteArrayInputStream(xmlstring.getBytes());
XMLInputFactory factory1 = XMLInputFactory.newInstance();
XMLStreamReader reader = factory1.createXMLStreamReader(bain);

while(reader.hasNext())
{
    reader.next();
    if(reader.getEventType==XMLStreamReader.START_ELEMENT)
    {
        if(reader.getLocalName().equals("price"))
        {
            //your logic
        }
    }
}

hope it helps..

希望能帮助到你..