简体   繁体   English

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

[英]How I need to get tag name of sub child in xml by comparing the attribute value and given string value using Java?

I have a xml file. 我有一个xml文件。 I need to get the sub child tag of the parent tag (Body) in xml file using Java. 我需要使用Java在xml文件中获取父标签(Body)的子子标签。 First I need to use DOM for reading an element and get xml file from my local machine drive. 首先,我需要使用DOM读取元素并从本地计算机驱动器获取xml文件。 I have one String varaible (Sring getSubChildValue = "181_paragraph_13") and I need to compare the value with each and every attribute Value in the Xml file. 我有一个String变量(Sring getSubChildValue =“ 181_paragraph_13”),我需要将值与Xml文件中的每个属性Value进行比较。 If the given Value may be in sub child tag,I cont able to get a Value. 如果给定的值可能在子标记中,则我无法获取值。

  1. what I need to do for compare the String variable and with Xml File 我需要做什么来比较String变量和Xml文件
  2. What I need to do for print the Tag name if the String value is equal to any attrinbute Value. 如果String值等于任何attrinbute值,我需要做的就是打印Tag名称。
  3. Example: (P) Tag is the sub child of Tag (Body) which contain the given String Value. 示例:(P)标签是标签(Body)的子子元素,其中包含给定的字符串值。 So I need to get tag name P. 因此,我需要获取标签名称P。
  4. How to avoid the Hard coding the sub-child Name to get the solution? 如何避免硬编码子名称以获得解决方案?

Example XML file: 示例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>

Example Java code: 示例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();
    }
}

//This Method is used to check which attribute contain given string Value : Hard code parent tag, But no other tag. //此方法用于检查哪个属性包含给定的字符串Value:硬代码父标记,但没有其他标记。

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());
            }
        }
    }
}
}

If you change your code to this: 如果将代码更改为此:

    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());
    }
}

you don't have the name of the attribute to be hardcoded. 您没有要硬编码的属性的名称。

EDIT: Added searchString as parameter. 编辑:添加searchString作为参数。

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

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