Java如何在JDOM中获取XML属性作为整数值?
在此示例中,您可以看到如何将xml属性值读取为整数值而不是字符串。JDOM提供了方法,例如getIntValue(),getLongValue(),getFloatValue(),getDoubleValue()以获得数值。对于布尔值,我们可以使用getBooleanValue()方法。
package org.nhooo.example.jdom; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import java.io.IOException; import java.io.StringReader; public class JDOMIntegerAttributeValue { public static void main(String[] args) { String xml = "<root><table width=\"100\"/></root>"; SAXBuilder builder = new SAXBuilder(); try { Document document = builder.build(new StringReader(xml)); Element child = document.getRootElement().getChild("table"); int tableWidth = child.getAttribute("width").getIntValue(); System.out.println("tableWidth = " + tableWidth); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/jdom/jdom2/2.0.6/jdom2-2.0.6.jar --> <dependency> <groupId>org.jdom</groupId> <artifactId>jdom2</artifactId> <version>2.0.6</version> </dependency>