简体   繁体   English

Java XML动态解析器

[英]Java XML dynamic parser

I'm looking for a simple solution. 我正在寻找一个简单的解决方案。

I have a xml file: 我有一个xml文件:

<properties>
    <property>
        <class>java.lang.String</class>
        <value>String value...</value>
    </property>
    <property>
        <class>java.lang.Boolean</class>
        <value>true</value>
    </property>
    <!-- ... others java lang wrapper class -->
</properties>

I would like to do a dynamic parser. 我想做一个动态解析器​​。

I know that I can read the xml with org.w3c.dom.* and org.w3c.dom.Node.getTextContent() I can get the value of the tag. 我知道我可以使用org.w3c.dom。*和org.w3c.dom.Node.getTextContent()读取xml,我可以获取标签的值。

Class<?> clazz = Class.forName(classTextContent);
// How to convert value to specific clazz?
// if/else (clazz)? Does not look a nice answer.

Any suggestion? 有什么建议吗?

[Edited] By reflection: [编辑]通过反思:

The variable "clazz " is a java.lang.Class, right? 变量“ clazz”是java.lang.Class,对吗? How can I convert textContent value (in String) to any wrapper type? 如何将textContent值(在String中)转换为任何包装类型?

Object objectValue = null;
Class<?> clazz = Class.forName(nodeClass.getTextContent());
String value = nodeValue.getTextContent();
if (clazz.equals(Boolean.class) { objectValue = Boolean.valueOf(value) }

valueOf could be a generic method that I could call using reflection... Integer, Float, Boolean, Long, Double support valueOf . valueOf可以是我可以使用反射调用的通用方法... Integer,Float,Boolean,Long,Double支持valueOf

Another way? 其他方式?

Object object = YourClass.class.getConstructor(new Class<?>[]{}).newInstance();

// if you want to use a constructor, let's say, for YourClass(int name, int id)

Object object = YourClass.class.getConstructor(new Class<?>[]{int.class, int.class}).newInstance(desiredName, desiredId);

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

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