簡體   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?

我有一個xml文件。 我需要使用Java在xml文件中獲取父標簽(Body)的子子標簽。 首先,我需要使用DOM讀取元素並從本地計算機驅動器獲取xml文件。 我有一個String變量(Sring getSubChildValue =“ 181_paragraph_13”),我需要將值與Xml文件中的每個屬性Value進行比較。 如果給定的值可能在子標記中,則我無法獲取值。

  1. 我需要做什么來比較String變量和Xml文件
  2. 如果String值等於任何attrinbute值,我需要做的就是打印Tag名稱。
  3. 示例:(P)標簽是標簽(Body)的子子元素,其中包含給定的字符串值。 因此,我需要獲取標簽名稱P。
  4. 如何避免硬編碼子名稱以獲得解決方案?

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

//此方法用於檢查哪個屬性包含給定的字符串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());
            }
        }
    }
}
}

如果將代碼更改為此:

    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作為參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM