java - 使用 Java 解析 XML 并获取元素值和属性值

标签 java xml parsing

我有一个 XML 文件,元素也有属性。 我有一个简单的 java 文件,它解析和打印文本文件中元素的值,而不是元素属性值。 请您帮忙打印属性值。 我正在粘贴下面的代码: --------employees.xml文件------------

<?xml version="1.0" encoding="UTF-8"?>

<Personnel>

  <Employee type="permanent">
    <Name>Seagull</Name>
    <Id>3674</Id>
    <Age>34</Age>
   </Employee>

  <Employee type="contract">
    <Name>Robin</Name>
    <Id>3675</Id>
    <Age>25</Age>
</Employee>

  <Employee type="permanent">
    <Name>Crow</Name>
    <Id>3676</Id>
    <Age>28</Age>
  </Employee>

</Personnel>

----------------------------StoreData.java---------------- --------------------------

import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult;

public class StoreData{
static public void main(String[] arg) {
    try{
        BufferedReader bf = new BufferedReader(new       InputStreamReader(System.in));
        System.out.print("Enter XML file name: ");
        String xmlFile = bf.readLine();
        File file = new File(xmlFile);
            if (file.exists()){
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(xmlFile);
                        //Create transformer
            Transformer tFormer = TransformerFactory.newInstance().newTransformer();
                     //Output Types (text/xml/html)
            tFormer.setOutputProperty(OutputKeys.METHOD, "text");
//              Write the document to a file
            Source source = new DOMSource(doc);
//              Create File  to view your xml data as (vk.txt/vk.doc/vk.xls/vk.shtml/vk.html)
            Result result = new StreamResult(new File("file.txt"));
            tFormer.transform(source, result);
            System.out.println("File creation successfully!");
        }
        else{
            System.out.println("File not found!");
        }
    }
    catch (Exception e){
        System.err.println(e);
        System.exit(0);
    }  
} }

最佳答案

由于您使用的是 org.w3c.dom,您可能会使用以下内容:

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xmlFile));
        Document doc = builder.parse(is);

        NodeList nodeList = doc.getElementsByTagName("Employee");

        for (int i = 0; i < nodeList.getLength(); i++) {                
            Node node = nodeList.item(i);

            if (node.hasAttributes()) {
                Attr attr = (Attr) node.getAttributes().getNamedItem("type");
                if (attr != null) {
                    String attribute= attr.getValue();                      
                    System.out.println("attribute: " + attribute);                      
                }
            }
        }

关于java - 使用 Java 解析 XML 并获取元素值和属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9758882/

相关文章:

c# - 使用命名空间将类序列化为 XML

c# - 在 C# 中对部分 SQL 进行 Lexing

python - Beautiful Soup 查找嵌套 div

java - 没有官方API获取Estimote Beacons的接近信息?

java - 在另一个线程中等待 Future 结果

android - 创建不需要在 XML 中设置 layout_width/height 的自定义 View

C# DateTime解析问题

java - 从文本文件中读取大量数据的最快方法

java - 如何生成连续的列表编号?

java - 为什么 JAXB 不能正确处理命名空间的子元素?