Это xml, который у меня есть в строковом формате.
<?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns:processRequestResponse xmlns:ns="http://service.soap.oneflexi.com"><ns:return>
<?xml version="1.0" encoding="UTF-8"?>
<ItemRs language="SG" currency="SGD">
<Items>
<Item>
<CategoryCode />
<CategoryDescription />
<ItemCode>356</ItemCode>
<ItemDescription>20% offer, Latest model</ItemDescription>
<Quantity />
<UnitPrice>24560</UnitPrice>
<ItemBigImagesURL>http://goo.gl/klCGG4</ItemBigImagesURL>
<ItemContent>Front Loading Washing Machine 6.5Kg Capacity 6 Motion Direct Drive</ItemContent>
<ErrorCode />
<ErrorMessage />
<Beaconid>2499</Beaconid>
</Item>
</Items>
<MID />
</ItemRs>
</ns:return>
</ns:processRequestResponse>
</soapenv:Body>
</soapenv:Envelope>
и вывод, который мне нужен, должен быть подмножеством вышеупомянутого xml, удаляющего заголовки мыла и другие теги. Как я могу достичь этого результата в java?
<ItemRs language="SG" currency="SGD">
<Items>
<Item>
<CategoryCode />
<CategoryDescription />
<ItemCode>356</ItemCode>
<ItemDescription>20% offer, Latest model</ItemDescription>
<Quantity />
<UnitPrice>24560</UnitPrice>
<ItemBigImagesURL>http://goo.gl/klCGG4</ItemBigImagesURL>
<ItemContent>Front Loading Washing Machine 6.5Kg Capacity 6 Motion Direct Drive</ItemContent>
<ErrorCode />
<ErrorMessage />
<Beaconid>2499</Beaconid>
</Item>
</Items>
<MID />
</ItemRs>
Пожалуйста, любая помощь будет оценена и спасибо заранее.
Я попытался использовать пример, приведенный в этом потоке: [1]: Java. Как извлечь полный блок XML.
Вот код Java
public static void main(String... args)
throws Exception
{
// String xml = "<A><B><id>0</id></B><B><id>1</id></B></A>";
String xml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.soap.oneflexi.com\"><soapenv:Header/><soapenv:Body><ser:processRequest><ser:in0><![CDATA[<BconRq language=\"SG\" currency=\"SGD\"><RqHeader><Date>20140614</Date><Time>162944</Time><TimeZone>GMT+06:00</TimeZone><MessageType>5320</MessageType><VersionNo>9005001</VersionNo><AppVersion>5.0.1</AppVersion><MerchantId>2003001</MerchantId><TerminalId>2004002</TerminalId><StanNo/><LastTxnRefNo/><OTP/></RqHeader><OfferMerchant/><OfferFlag>Y</OfferFlag><BconId>1234</BconId><Items><Item><ItemCode>VC01</ItemCode></Item></Items></BconRq>]]></ser:in0><ser:in4>?</ser:in4></ser:processRequest></soapenv:Body></soapenv:Envelope>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
XPath xPath = XPathFactory.newInstance().newXPath();
Node result = (Node)xPath.evaluate(" Soapenv:Envelope/Soapenv:Body/ns:processRequestResponse/ns:return/BconRs[language=\"SG\"]", doc, XPathConstants.NODE);
// Node result = (Node)xPath.evaluate("A/B[id = '1']", doc, XPathConstants.NODE);
// Soapenv:Envelope/Soapenv:Body/ns:processRequestResponse/ns:return/BconRs[language="SG"]
System.out.println(nodeToString(result));
}
private static String nodeToString(Node node)
throws TransformerException
{
StringWriter buf = new StringWriter();
Transformer xform = TransformerFactory.newInstance().newTransformer();
xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
xform.transform(new DOMSource(node), new StreamResult(buf));
return(buf.toString());
}
Вероятно, я думаю, что в XPATH может произойти ошибка, пересекающая узел ItemRs.
Как вы также подозревали, XPath выглядит некорректно. Вы можете попробовать этот простой XPath:
//ItemRs[@language='SG']
Чтобы ссылаться на атрибут в XPath, вам нужно использовать @
в начале имени атрибута. И я стараюсь избегать упоминания префиксов пространства имен в XPath, потому что обычно нам нужно каким-то образом зарегистрировать URI-сопоставление пространства имен для пространства имен (и я не уверен, как это сделать в Java, я больше в.NET).