共計 1966 個字符,預計需要花費 5 分鐘才能閱讀完成。
在 Java 中,你可以使用 DOM 或 SAX 解析器來讀取本地 XML 文件。
使用 DOM 解析器:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class ReadXMLFile {public static void main(String[] args) {try {// 創建 DocumentBuilderFactory 實例
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 創建 DocumentBuilder 實例
DocumentBuilder builder = factory.newDocumentBuilder();
// 使用 DocumentBuilder 解析 XML 文件并返回 Document 對象
Document document = builder.parse("path_to_xml_file");
// 獲取根元素
Element root = document.getDocumentElement();
// 獲取所有子元素
NodeList nodeList = root.getChildNodes();
// 遍歷子元素
for (int i = 0; i < nodeList.getLength(); i++) {Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {Element element = (Element) node;
// 獲取元素的標簽名和文本內容
String tagName = element.getTagName();
String textContent = element.getTextContent();
// 處理元素...
}
}
} catch (Exception e) {e.printStackTrace();
}
}
}
使用 SAX 解析器:
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ReadXMLFile {public static void main(String[] args) {try {// 創建 SAXParserFactory 實例
SAXParserFactory factory = SAXParserFactory.newInstance();
// 創建 SAXParser 實例
SAXParser saxParser = factory.newSAXParser();
// 創建一個自定義的 DefaultHandler 實例
DefaultHandler handler = new DefaultHandler() {boolean elementFlag = false;
// 開始解析元素時調用
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {elementFlag = true;
}
// 結束解析元素時調用
public void endElement(String uri, String localName, String qName) throws SAXException {elementFlag = false;
}
// 解析元素內容時調用
public void characters(char ch[], int start, int length) throws SAXException {if (elementFlag) {String content = new String(ch, start, length);
// 處理元素內容...
}
}
};
// 使用 SAXParser 解析 XML 文件
saxParser.parse("path_to_xml_file", handler);
} catch (Exception e) {e.printStackTrace();
}
}
}
在代碼中,將 "path_to_xml_file" 替換為你要讀取的本地 XML 文件的路徑。
丸趣 TV 網 – 提供最優質的資源集合!
正文完