验证java中的xml数据

时间:2013-09-11 09:13:30

标签: java xml

我的交易xml如下所示

<?xml version= "1.0"?>
<transactionlist>
<transaction action="c">
    <transactionid>t004</transactionid>
    <transactiondate>11/06/2013</transactiondate>
    <merchantdetails>Sony wholesale Dealer</merchantdetails>
    <itempurchased>3</itempurchased>
    <amount>40399</amount>
    <description>sony laptops</description>
</transaction>
<transaction action="d">
    <transactionid>t003</transactionid>
</transaction>
<transaction action="u">
    <transactionid>T001</transactionid>
    <transactiondate>20/08/2013</transactiondate>
    <merchantdetails>samsung Axses</merchantdetails>
    <itempurchased>1</itempurchased>
    <amount>40000</amount>
    <description>samsung smart phone</description>
</transaction>
</transactionlist>

我已经在上面的xml中解析了itempurchased元素,并将其存储在整数变量中。如何仅针对数字验证itempurchased。那就是我想检查itempurchased是否是数字。请提供建议

2 个答案:

答案 0 :(得分:2)

最佳方法应该是针对xsd验证xml,其中itempurchased的类型为xsd:int

低于xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="transactionlist">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="transaction">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="transactionid" type="xs:string" />
              <xs:element minOccurs="0" name="transactiondate" type="xs:string" />
              <xs:element minOccurs="0" name="merchantdetails" type="xs:string" />
              <xs:element minOccurs="0" name="itempurchased" type="xs:int" />
              <xs:element minOccurs="0" name="amount" type="xs:int" />
              <xs:element minOccurs="0" name="description" type="xs:string" />
            </xs:sequence>
            <xs:attribute name="action" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

这里Validating XML against XSD 验证xml对xsd

的代码

答案 1 :(得分:0)

如果要将xml封送到java bean,那么可以尝试使用Java6 Bean Validation Framework。在这里阅读更多相关信息:

http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html

就像在bean上添加注释一样简单:

public class MyXMLBean {
    @Max(10)
    @Min(5) 
    private int itempurchased;
}

上述bean将允许在注释中提到的最小值和最大值之间设置itempurchased的值。