2013-04-25 62 views
0

我想读取下面的使用JDOM的XML字符串响应,但不知道如何解析?你能帮我么? 我想下面的代码解析:Xml namspace使用JDOM解析

org.jdom.Element rootNode = document.getRootElement(); 

List<?> list = rootNode.getChildren("QuotationResponse"); 
for(int i = 1 ; i <= list.size() ; i++) { 
    Element node = (Element) list.get(i); 
    String documentDate = node.getAttribute("documentDate"); 
    String transactionType = node.getAttribute("transactionType"); 
} 

XML:

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

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><VtEnvelope 

xmlns="un:vtinc:o-series:tps:6:0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 

<Login><UserName>user</UserName> 
<Password>abcd</Password> 
</Login> 
<QuotationResponse documentDate="2011-03-24" transactionType="SALE"><Customer><Destination taxAreaId="1230000"><City>Dallas</City> 
<MainDivision>TX</MainDivision> 
<SubDivision>Chester</SubDivision> 
<PostalCode>75038</PostalCode> 
<Country>USA</Country> 
</Destination> 
</Customer> 
<SubTotal>1000.0</SubTotal> 
<Total>1060.0</Total> 
<TotalTax>60.0</TotalTax> 
<LineItem lineItemId="1" lineItemNumber="1" taxDate="2013-04-25"><Product productClass="product class attribute value">product code value</Product> 
<Quantity>1.0</Quantity> 
<FairMarketValue>1000.0</FairMarketValue> 
<UnitPrice>1000.0</UnitPrice> 
<ExtendedPrice>1000.0</ExtendedPrice> 
<Taxes taxResult="TAXABLE" taxType="SALES" situs="DESTINATION" taxCollectedFromParty="BUYER"><Jurisdiction jurisdictionLevel="STATE" jurisdictionId="3051">Texas</Jurisdiction> 
<CalculatedTax>60.0</CalculatedTax> 
<EffectiveRate>0.06</EffectiveRate> 
<Taxable>1000.0</Taxable> 
<Imposition impositionType="General Sales and Use Tax">Sales and Use Tax</Imposition> 
<TaxRuleId>121</TaxRuleId> 
</Taxes> 
<TotalTax>60.0</TotalTax> 
</LineItem> 
</QuotationResponse> 
</VtEnvelope></S:Body></S:Envelope> 

回答

1

您需要使用特定的名称空间的getChildren()方法。你想要的命名空间是 “非:vtinc:邻系列:TPS:6:0”

Namespace ns = Namespace.getNamespace("un:vtinc:o-series:tps:6:0"); 
List<?> list = rootNode.getChildren("QuotationResponse", ns); 

如果您使用JDOM 2.x中,第二行可能是:

Namespace ns = Namespace.getNamespace("un:vtinc:o-series:tps:6:0"); 
List<Element> list = rootNode.getChildren("QuotationResponse", ns); 

和你的整个事情可能是:

Namespace ns = Namespace.getNamespace("un:vtinc:o-series:tps:6:0"); 
for(Element node : rootNode.getChildren("QuotationResponse", ns)) { 
    String documentDate = node.getAttribute("documentDate"); 
    String transactionType = node.getAttribute("transactionType"); 
} 

编辑:好的,你仍然有问题。我看到一些现在错误的东西。

您应该使用JDOM 2.0.4。这将有助于类型铸造。你以某种方式将一个Attribute对象放入String中。这应该不可能编译!

String documentDate = node.getAttributeValue("documentđate") 

最后,QuotationResponse是根元素的一个孩子,但S的:身体....然后VtEncelope。您将需要使用正确的命名空间来访问它们。你需要让你的文档结构正确。

+0

谢谢你的回应,但我仍然得到空值。你可以给我更多的投入。感谢您的帮助。 – 2013-04-25 18:28:23

+0

rolfl!非常感谢你的努力和友好的合作。我仍然处于这个问题的中心。我只能得到根和身体的孩子。我试图从该XML中获取所有元素和文本。我的主要问题是为什么我无法获得QuotationResponse的孩子?如何获得孩子和客户元素的文本?请救救我帮忙! 谢谢........ – 2013-04-26 14:17:34