Анализ пространства имен Xml с использованием JDOM

Я пытаюсь прочитать следующий ответ XML String с помощью 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>

person NabRaj_Baitadi    schedule 25.04.2013    source источник


Ответы (1)


Вам нужно использовать метод getChildren(), специфичный для пространства имен. Вам нужно пространство имен "un:vtinc:o-series: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 documentDate = node.getAttributeValue("documentđate")

Наконец, QuotationResponse является не дочерним элементом корневого элемента, а потомком S:Body.... и затем VtEncelope. Вам нужно будет получить к ним доступ с правильными пространствами имен. Вам нужно правильно составить структуру документа.

person rolfl    schedule 25.04.2013
comment
Спасибо за ваш ответ, но я все равно получаю нулевое значение. Можете ли вы дать мне еще несколько входных данных. Спасибо за помощь. - person NabRaj_Baitadi; 25.04.2013
comment
Рольфл! Большое спасибо за ваши усилия и любезное сотрудничество. Я все еще в середине вопроса. Я могу получить только детей корня и тела. Я пытаюсь получить все элементы и текст из этого XML. Мой главный вопрос: почему я не могу получить детей от QuotationResponse? Как получить дочерние элементы и текст элемента клиента? Пожалуйста, спаси меня, сделав одолжение! Спасибо........ - person NabRaj_Baitadi; 26.04.2013