如何生成Java文件,意味着生成类方法属性的名称,而不使用XML中的任何API
我的XML文件:来源
<class name="person">
<Attribut type="int">Age</Attribut>
<Attribut type="String">Name</Attribut>
</class>
到java文件:
public class person {
int age;
String Name;
}
非常感谢您的帮助
谢谢
答案 0 :(得分:1)
如果您仍想自己动手。您可以查看此简化示例。
警告:
示例代码
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
public class XMLStreamReaderDemo {
public static void main(String[] args) throws Exception {
String xmlFileName = "source.xml";
StringBuilder javaSource = transform(xmlFileName);
System.out.println(javaSource);
}
static StringBuilder transform(String xmlFileName) throws
FactoryConfigurationError, IOException, XMLStreamException {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader parser = null;
StringBuilder source = new StringBuilder();
try (FileInputStream inputStream = new FileInputStream(xmlFileName)) {
parser = factory.createXMLStreamReader(inputStream);
while (parser.hasNext()) {
switch (parser.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
processStartElement(parser, source);
break;
case XMLStreamConstants.CHARACTERS:
processCharacters(parser, source);
break;
case XMLStreamConstants.END_ELEMENT:
processEndElement(parser, source);
break;
default:
break;
}
parser.next();
}
} finally {
if (parser != null) {
parser.close();
}
}
return source;
}
static void processEndElement(XMLStreamReader reader, StringBuilder sb) {
String element = reader.getLocalName();
if ("class".equals(element)) {
sb.append("}");
} else if ("Attribut".equals(element)) {
sb.append(";\n");
}
}
static void processCharacters(XMLStreamReader reader, StringBuilder sb) {
if (!reader.isWhiteSpace()) {
sb.append(" ").append(reader.getText());
}
}
static void processStartElement(XMLStreamReader reader, StringBuilder sb) {
String element = reader.getLocalName();
if ("class".equals(element)) {
sb.append("public class ")
.append(reader.getAttributeValue(0))
.append(" {\n");
} else if ("Attribut".equals(element)) {
sb.append(" ")
.append(reader.getAttributeValue(0));
}
}
}
假设source.xml
包含
<class name="person">
<Attribut type="int">Age</Attribut>
<Attribut type="String">Name</Attribut>
</class>
代码打印
public class person {
int Age;
String Name;
}
&#34; only&#34;你要做的事情:实现所有缺失的部分。如果这仍然包含太多&#34; XML API ......好吧......编写自己的解析器。 ; - )
答案 1 :(得分:0)
您可以从xsd or xml
文件生成java类,而无需使用任何java代码或类文件,使用jaxb https://jaxb.java.net/或java中提供的exe文件默认位于jdk bin文件夹xjc.exe
https://docs.oracle.com/javase/8/docs/technotes/tools/unix/xjc.html
上的文档