简体   繁体   English

Java XML解析器?

[英]Java XML parser?

I'm currently converting a program I wrote in Visual Basic .NET (the 2005 variety) into Java. 我目前正在将我在Visual Basic .NET(2005年版)中编写的程序转换为Java。 It used built-in XML methods to parse and generate the user's saved data, does Java have an equivalent feature built in or am I going to have to change file processing implementations? 它使用内置的XML方法来解析和生成用户保存的数据,Java是否具有内置的等效功能,或者我是否必须更改文件处理实现? (I'd rather not, there's a lot of code I'd have to change.) (我不愿意,有很多代码我不得不改变。)

Yes, Java can parse XML. 是的,Java可以解析XML。 Here's an example that takes in a String that contains XML and builds a Document object out of it: 这是一个示例,它接受包含XML的String并从中构建Document对象:

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(xml));
Document document = documentBuilder.parse(inputSource);

You can then use the XPath API to query the dom. 然后,您可以使用XPath API查询dom。 Here's a tutorial/writeup about it. 这是关于它的教程/写作

As far as serializing objects to XML, the official implementation is JAXB and it is part of Java since 1.6. 至于将对象序列化为XML,官方实现是JAXB,它是1.6的Java的一部分。 Here's a simple example. 这是一个简单的例子。 It will let you serialize and deserialize to and from XML. 它将允许您对XML进行序列化和反序列化。

You can also create a DOM object manually and add nodes to it, but it's a little more tedious: 您也可以手动创建DOM对象并向其添加节点,但这有点单调乏味:

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();

Element rootNode = document.createElement("root");

Element childNode = document.createElement("child");
childNode.setTextContent("I am a child node");
childNode.setAttribute("attr", "value");

rootNode.appendChild(childNode);
document.appendChild(rootNode);

I'm assuming that you mean that the properties/structure was generated through the classes/beans themselves? 我假设您的意思是属性/结构是通过类/ bean本身生成的? If so, then the answer is no [without an third party component]. 如果是这样,那么答案就是[没有第三方组件]。 I've used XStream before, and that is about the closest that I've gotten to .NET's XML Class serialization. 我之前使用过XStream,这是我最接近.NET的XML类序列化的。

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

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