我如何通过使用Java比较属性值和给定的字符串值来获取xml中子子的标记名?

时间:2016-03-23 13:44:26

标签: java xml

我有一个xml文件。我需要使用Java在xml文件中获取父标记(Body)的子子标记。首先,我需要使用DOM来读取元素 并从我的本地计算机驱动器获取xml文件。我有一个字符串变量(Sring getSubChildValue =" 181_paragraph_13")我需要比较值 使用Xml文件中的每个属性值。如果给定的值可能在子子标签中,我可以获得一个值。

  1. 我需要做什么来比较String变量和Xml文件
  2. 如果String值等于任何attrinbute值,我需要做什么来打印Tag名称。
  3. 示例:(P)Tag是Tag(Body)的子子节点,它包含给定的String Value。所以我需要获得标签名称P.
  4. 如何避免硬编码子子名称以获得解决方案?
  5. 示例XML文件:

    <parent>
    <Body class="student" id="181_student_method_3">
    <Book class="Book_In_School_11" id="181_student_method_11"/>
    <subject class="subject_information " id="181_student_subject_12"/>
    <div class="div_passage " id="181_div_method_3">
    <p class=" paragraph_book_name" id="181_paragraph_13">
    <LiberaryBook class="Liberary" id="181_Liberary_9" >
    <Liberary class="choice " 
    id="Liberary_replace_1" Uninversity="University_Liberary_1">
    Dubliners</Liberary>
    <Liberary class="choice "
    id="Liberary_replace_2"  Uninversity="University_Liberary_2">
    Adventure if sherlock Holmes</Liberary>
    <Liberary class="choice "
    id="Liberary_replace_3"   Uninversity="University_Liberary_3">
    Charlotte’s Web</Liberary>
    <Liberary class="choice " 
    id="Liberary_replace_4" Uninversity="University_Liberary_4">
    The   Outsiders</Liberary>
    </LiberaryBook>
    </p>
    </div>
    </Body>
    </parent>
    

    示例Java代码:

    import java.io.File;
    import java.io.IOException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    public class PerfectTagChange {
    public static void main(String[] args) {
        String filePath = "/xmlfile/Xml/check/sample.xml";
        File xmlFile = new File(filePath);
        DocumentBuilderFactory 
     dbFactory =   DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);
            doc.getDocumentElement().normalize();
            Element root = doc.getDocumentElement(); 
            changeValue(root,doc);
            doc.getDocumentElement().normalize();
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("/xmlfile/Xml/check/Demo.xml"));
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(source, result);
            System.out.println("XML file updated successfully");
    
        } catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
            e1.printStackTrace();
        }
    }
    

    //此方法用于检查哪个属性包含给定的字符串值:硬代码父标记,但没有其他标记。

    private static void changeValue(Node someNode,Document doc) {
        Sring getSubChildValue = "181_paragraph_13"
        NodeList childs = someNode.getChildNodes();
         for (int in = 0; in < childs.getLength();) {
             Node child = childs.item(in);
             if (child.getNodeType() == Document.ELEMENT_NODE) {
                if (child.getNodeName().equalsIgnoreCase("Body") ) {
                //If I hard code the ID here on getNamedItem("id"),
                  If the  attribute Name got Changed from ID to Name 
                  it will be in problem.
                //3.What is the solution for solving the problem.
                if(child.getAtrribute.getNamedItem("id").getNodeValue().equals(getSubChildValue)){ 
                system.out.println(child.getAtrribute.getNamedItem("id").getNodeValue());
                }
            }
        }
    }
    }
    

1 个答案:

答案 0 :(得分:1)

如果您将代码更改为:

    private static void changeValue(Node someNode, Document doc, String searchString) throws Exception {
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xPath.evaluate("//*[@*=\"" + searchString + "\"]", 
                                                doc.getDocumentElement(),
                                                XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println("Tagname: " + nodes.item(i).getNodeName());
    }
}

您没有要硬编码的属性的名称。

修改 添加了searchString作为参数。