Search for element value in an XML file

后端 未结 2 521
迷失自我
迷失自我 2021-01-20 14:29

In a given XML file, I\'m trying to search for the presence of a string using XPath in Java. However, even though the string is there, my output is always comi

2条回答
  •  粉色の甜心
    2021-01-20 14:54

    I tested this...

    expr =xpath.compile("/article/body/section/region[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'perfect')]");
    

    Against

    intro1

    perfect Perfect

    1 task objectives

    pErFeCt Not Perfect

    1 task objectives

    object1 This is the Perfect Word I am looking for

    Using...

    import java.io.File;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathExpression;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    public class TestXML05 {
    
        public static void main(String[] args) {
            try {
    
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                Document doc = factory.newDocumentBuilder().parse(new File("Sample.xml"));
    
                XPathFactory xFactory = XPathFactory.newInstance();
                XPath xPath = xFactory.newXPath();
                XPathExpression exp = xPath.compile("/article/body/section/region[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'perfect')]");
    
                NodeList nl = (NodeList)exp.evaluate(doc.getFirstChild(), XPathConstants.NODESET);
                for (int index = 0; index < nl.getLength(); index++) {
    
                    Node node = nl.item(index);
                    System.out.println(node.getTextContent());
    
                }
    
    
            } catch (Exception ex) {
                Logger.getLogger(TestXML05.class.getName()).log(Level.SEVERE, null, ex);
            }
    
        }
    }
    

    Which outputted...

    perfect
    Perfect
    pErFeCt
    Not Perfect
    This is the Perfect Word I am looking for
    

提交回复
热议问题