简体   繁体   English

通过用户输入在Java中提供的特定属性获取元素

[英]Get element by specific attribute given by user input in java

I am new in Java Programming. 我是Java编程的新手。 I have an assignment where i have to get the element of specific attribute.I am using netbeans for my project. 我有一个任务,我必须获取特定属性的元素。我正在为项目使用netbeans。 The attribute is taken from the user which will be searched in the xml file and the element of that attribute will be displayed. 该属性取自将在xml文件中搜索的用户,并且将显示该属性的元素。 I have searched alot but couldn't find any solution.Please help me out. 我已经搜索了很多,但找不到任何解决方案。请帮帮我。 I am using XPathFactory. 我正在使用XPathFactory。 For example if i enter id in the input then it should display the element ie gemstone.The code doesnot show any error it compiles correctly but it doesnot show any output. 例如,如果我在输入中输入id,则它应显示元素,例如gemstone。代码未显示任何错误,但可以正确编译,但不显示任何输出。 Following is the code for java and my xml file. 以下是java和我的xml文件的代码。

java file Java文件

 String data;
       Scanner input = new Scanner (System.in);
       System.out.println("Enter Attribute whose Element you want to be displayed ");
       data = input.nextLine();
       System.out.println(" \n ");
       try {
    File fXmlFile = new File("stonesorg.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        NodeList node;
        node = (NodeList) xpath.evaluate(data, doc, XPathConstants.NODESET);
        for (int x = 0; x < node.getLength(); x++)
        {
            System.out.print(node.item(x).getNodeName()+" ");
        }

         System.out.println(" \n "); 
       }
       catch(ParserConfigurationException | SAXException | IOException | DOMException e)
       {

       }   
    }

xml file xml文件

<gemstone id = "G1">
        <Name name= "Amethyst"> 
        <namehistory> The name comes from the Koine Greek. </namehistory>
        <namemeaning> Intoxicate </namemeaning>
        </Name>
        <identification> 
        <color> Violet  </color>
        <composition> Quartz,Silica (silicon dioxide, SiO2)</composition>
        <mohsScale> 7–lower in impure varieties</mohsScale>
        <crystalSystem> Trigonal</crystalSystem>
        <category> Silicate mineral </category>
        </identification>
        <history>It is from Magaliesburg, South Africa.The Greeks believed amethyst gems could prevent intoxication, while medieval European soldiers wore amethyst amulets as protection in battle in the belief that amethysts heal people and keep them cool-headed.</history>
        <geographicaldistribution>
            <country>Brazil</country>
            <country>Russia</country>
            <country>South Korea</country>
            <country>Colorado</country>
            <country>Texas</country>
            <country>Pennsylvania</country>
            <country>Ontario</country>
        </geographicaldistribution>
        <birthstone>  Birthstone for February   </birthstone>
        <properties>
            <meltingpoint> 
                            <celsius> 1650±75 °C </celsius>
                            <fahrenheit>3002 ±167°F </fahrenheit>
            </meltingpoint>
            <solubility> Insoluble in common solvents </solubility>
            <gravity> 2.65 constant </gravity>
        </properties>
    </gemstone>

First of all: never suppress exceptions (if you did not shrink code sample). 首先:永远不要抑制异常(如果您不缩减代码示例)。 At least put e.printStackTrace(); 至少放e.printStackTrace(); there 那里

catch(ParserConfigurationException | SAXException | IOException | DOMException e)
   {
     e.printStackTrace();
   }   

Second: your code must not compile - one exception is missing in catch - XPathException 第二:你的代码不能编译-唯一的例外是缺少catch - XPathException

Third (and main): after adding XPathException your code is working, but you need to be aware what XPath you enter as input. 第三(也是主要的):添加XPathException您的代码即可运行,但是您需要知道输入的XPath是什么。 (please read docs and tutorials about XPath). (请阅读有关XPath的文档和教程)。

It is not that simple as just a Node name you want to get. 它并不像您想要的节点名称那样简单。 As long as you run it from top Document - yes you can enter gemstone - because it is a root element, but for other nodes you have to provide valid XPath - otherwise you will get nothing. 只要从顶部文档运行它-是的,您就可以输入gemstone因为它是根元素,但是对于其他节点,您必须提供有效的XPath-否则您将一无所获。

BTW try to make your print statement a little more informative for debugging like: 顺便说一句,尝试使您的打印语句对调试更有益,例如:

System.out.println(node.item(x).getNodeName()+" " + node.item(x).getTextContent());

Later you can make more nice... 以后你可以做得更好...

So, try some examples: 因此,请尝试一些示例:

  • gemstone
  • gemstone/Name/@name
  • gemstone/geographicaldistribution/*
  • gemstone/geographicaldistribution/country
  • //country[3]
  • //country[text()='Texas']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM