【问题标题】:XML parsing of data java数据java的XML解析
【发布时间】:2012-04-11 13:54:10
【问题描述】:

我有以下 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>

<root>
    <eq1>-3.874999999999* Math.pow(x, 4.0) + 48.749999999993* Math.pow(x, 3.0)</eq1>
    <eq2>-0.166666666667* Math.pow(x, 4.0) + 2.166666666667* Math.pow(x, 3.0)</eq2>
</root>

我想解析这两个方程并将它们放入变量中以供进一步计算。我目前使用的方法是解析它们并将它们放在一个字符串中,但它不起作用,因为我需要使用方程式执行计算。

有没有更好的方法可以解决这个问题?提前致谢。

【问题讨论】:

标签: java xml parsing xml-parsing


【解决方案1】:

您可以使用 JAXB 将 XML 文件解组为具有这些字段的自定义对象。

您的对象可能看起来像:

@XmlRootElement
public class Equations {

    String eq1;
    String eq2;

    // create getters and setters as well
    // and put the @XmlElement annotation on the setters
}

然后从 Equations 对象中使用它们。 (例如equations.getEq1());

这是一个非常简单快速的 JAXB 简介:http://www.mkyong.com/java/jaxb-hello-world-example/

关于方程的执行,一种方法是解析字符串,看看你有哪些指令和数字,然后把它们放在堆栈上,然后当一切都被解析后,执行操作(你会得到数字和操作在堆栈上)。也许这需要更多的工作,但这绝对是解决问题的有趣方式。

【讨论】:

    【解决方案2】:

    试试BeanShell 评估器:

    import bsh.EvalError;
    import bsh.Interpreter;
    
    public class BeanShellInterpreter {
    
      public static void main(String[] args) throws EvalError {
    
        Interpreter i = new Interpreter();  // Construct an interpreter
        i.set("x", 5);
        // Eval a statement and get the result
        i.eval("eq1 = (-3.874999999999* Math.pow(x, 4.0) + 48.749999999993* Math.pow(x, 3.0))");
        System.out.println( i.get("eq1") );
      }
    }
    

    【讨论】:

    • 我认为Sysout必须是System.out.println( i.get("bar") );
    • 我会调查的。这必须在移动应用程序上实现,所以我认为用尊重的方程创建 2 个变量更有意义,因为 250k 库对于应用程序来说相当大。
    猜你喜欢
    • 2012-04-08
    • 2015-07-12
    • 1970-01-01
    • 2012-11-17
    • 2012-03-07
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 2019-01-06
    相关资源
    最近更新 更多