java - Java 中来自 xml 的动态属性

标签 java xml

我正在摆弄一个想法,但无法捕获它。

我有一个 xml 文件,其中包含 100 多个属性,定义了一个较大程序的运行时环境。它们通过类公开为变量。目前,对于 xml 文件中的每个选项,类中都有一个变量以及公共(public) getter 和私有(private) setter。

每次我们需要一个新选项时,我们都必须在 xml 文件中定义它,并在 RuntimenEnvironment 类中创建变量和方法。

现在,我想做的是这样的:我想以这样的方式重写该类,它将 xml 文件中的新选项公开为 vars,而不必接触该类。

我的 xml 文件使用此结构:

<option>
  <name>theName</name>
  <type>eg int</type>
  <value>20</value>
  <constant>THE_NAME</constant>
</option>

我可以用 java 编写代码,在运行时动态创建变量并通过方法公开它们,而无需实际编写该方法吗?

这可能吗?

提前致谢,

克里斯

最佳答案

我能想到的几个选项是:

  • 如果名称是唯一的,则可以使用名称作为键来填充映射。

  • 如果您只对选项感兴趣,则可以列出选项列表 从 XML 填充。

下面是使用SAX解析器实现的示例代码

处理程序类

public class OptionsParser extends DefaultHandler {
    private final StringBuilder valueBuffer = new StringBuilder();
    private final Map<String, Option> resultAsMap = new HashMap<String, Option>();
    private final List<Option> options = new ArrayList<Option>();

    //variable to store the values from xml temporarily
    private Option temp;

    public List<Option> getOptions() {
        return options;
    }

    public Map<String, Option> getResultAsMap() {
        return resultAsMap;
    }

    @Override
    public void startElement(final String uri, final String localName, final String qName,
            final Attributes attributes) throws SAXException {
        if("option".equalsIgnoreCase(qName)) {
            temp = new Option();
        }
    }

    @Override
    public void endElement(final String uri, final String localName, final String qName)
            throws SAXException {
        //read the value into a string to set them to option object
        final String value = valueBuffer.toString().trim();
        switch (qName) {
        case "name":
            temp.setName(value);
            // set the value into map and name of the option is the key
            resultAsMap.put(value, temp);
            break;
        case "type":
            temp.setType(value);
            break;
        case "value":
            temp.setValue(value);
            break;
        case "constant":
            temp.setConstant(value);
            break;
        case "option":
            // this is the end of option tag add it to the list
            options.add(temp);
            temp = null;
            break;
        default:
            break;
        }
        //reset the buffer after every iteration
        valueBuffer.setLength(0);
    }

    @Override
    public void characters(final char[] ch, final int start, final int length)
            throws SAXException {
        //read the value into a buffer
        valueBuffer.append(ch, start, length);
    }
}

期权 POJO

public class Option {

    private String name;
    private String type;
    private String value;
    private String constant;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getConstant() {
        return constant;
    }

    public void setConstant(String constant) {
        this.constant = constant;
    }
}

输入 XML

<options>
    <option>
        <name>option1</name>
        <type>int</type>
        <value>20</value>
        <constant>const1</constant>
    </option>
    <option>
        <name>option2</name>
        <type>string</type>
        <value>testValue</value>
        <constant>const2</constant>
    </option>
</options>

示例主类

public class ParseXML {
        public static void main(String[] args) {
            final OptionsParser handler = new OptionsParser();
            try {
                SAXParserFactory.newInstance().newSAXParser()
                        .parse("C:/luna/sample/inputs/options.xml", handler);
            } catch (SAXException | IOException | ParserConfigurationException e) {
                System.err.println("Somethig went wrong while parsing the input file the exception is -- " + e.getMessage() + " -- ");
            }
            Map<String, Option> result = handler.getResultAsMap();
            Collection<Option> values = result.values();
            for (Option option : values) {
                System.out.println(option.getName());
            }

        }
    }

关于java - Java 中来自 xml 的动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26601849/

相关文章:

java - 如何对相同的表达式进行不同的评估?

java - antisamy 解析器强制关闭标记

php - 在 NuSOAP 上创建重复标签

html - 用于在另一个节点之后获取节点的 XPath 语法?

python - 雅虎体育 API XML 命名空间找不到元素

java - 如何在浏览器关闭后保留 session ?

java - 如何使用计时器减慢 for 循环速度

java - 接口(interface)、抽象和类

html - Xpath选择带有多个空格和换行符的html

xml - 为什么 COBOL 生成的 XML 中缺少编码属性?