Parsing XML response in VBA - vba

I am calling a webservice from Excel macro but not able to parse the response XML. The Structure of the Response is as follows -
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:typ="http://xmlns.oracle.com/oracle/apps/marketing/commonMarketing/mktImport/model/types/">
<env:Header>
<wsa:Action>http://xmlns.oracle.com/oracle/apps/marketing/commonMarketing/mktImport/model//ImportPublicService/getImportActivityLogsResponse</wsa:Action>
<wsa:MessageID>urn:uuid:bffbffe9-a379-46bb-8205-7f6b5d15a0f5</wsa:MessageID>
</env:Header>
<env:Body>
<ns0:getImportActivityLogsResponse xmlns:ns0="http://xmlns.oracle.com/oracle/apps/marketing/commonMarketing/mktImport/model/types/">
<ns2:result xsi:type="ns1:ImportServiceLogs" xmlns:ns2="http://xmlns.oracle.com/oracle/apps/marketing/commonMarketing/mktImport/model/types/" xmlns:ns1="http://xmlns.oracle.com/oracle/apps/marketing/commonMarketing/mktImport/model/" xmlns:ns0="http://xmlns.oracle.com/adf/svc/types/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns1:LogFileName>log-test_contact_01-02_20150422171310_pverma Data File.csv</ns1:LogFileName>
<ns1:LogFileContent>
<xop:Include href="cid:ec277fd6-76e2-4ae3-9e8b-1b14c446adf8" xmlns:xop="http://www.w3.org/2004/08/xop/include"/>
</ns1:LogFileContent>
<ns1:ErrorLogFileName>error-test_contact_01-02_20150422171310_pverma Data File.csv</ns1:ErrorLogFileName>
<ns1:ErrorLogFileContent>
<xop:Include href="cid:d41bacf8-3134-4cd5-80b7-5a68c2b271ed" xmlns:xop="http://www.w3.org/2004/08/xop/include"/>
</ns1:ErrorLogFileContent>
<ns1:ExceptionLogFileName>exception-test_contact_01-02_20150422171310_pverma Data File.csv</ns1:ExceptionLogFileName>
<ns1:ExceptionLogFileContent>
<xop:Include href="cid:4aa55e1b-1d4d-48be-bdd0-66200de496ee" xmlns:xop="http://www.w3.org/2004/08/xop/include"/>
</ns1:ExceptionLogFileContent>
<ns1:BatchId xsi:nil="true"/>
</ns2:result>
</ns0:getImportActivityLogsResponse>
</env:Body>
</env:Envelope>
This response contains the flat files. I have to parse these files from above XML.
Please suggest any solution over it. Help will be much appreciated.

You can use MSXML2 and XPath:
Dim xmldoc As Object
Dim xmlnode As Object
Set xmldoc = CreateObject("MSXML2.DOMDocument")
xmldoc.setProperty "SelectionLanguage", "XPath"
xmldoc.loadXML response '//The XML Response string
For Each xmlnode In xmldoc.SelectNodes("//*[contains(name(),'LogFileName')]")
Debug.Print xmlnode.Text
Next
For early binding reference Mictosoft XML v3.0 or v6.0.

Related

serializing soap response in vb.net

Using response As WebResponse = request.GetResponse()
Using rd As New StreamReader(response.GetResponseStream())
Dim soapResult As String = rd.ReadToEnd()
SerializeCollection(soapResult)
the soapResult generate the following :
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<createShipmentResponse xmlns="http://www.royalmailgroup.com/api/ship/V2">
<integrationHeader>
<dateTime xmlns="http://www.royalmailgroup.com/integration/core/V1">2016-03-23T06:55:32</dateTime>
<version xmlns="http://www.royalmailgroup.com/integration/core/V1">2</version>
<identification xmlns="http://www.royalmailgroup.com/integration/core/V1">
<applicationId>RMG-API-G-01</applicationId>
<transactionId>730222611</transactionId>
</identification>
</integrationHeader>
<integrationFooter>
<errors xmlns="http://www.royalmailgroup.com/integration/core/V1">
<error>
<errorCode>E1105</errorCode>
<errorDescription>The countryCode specified is not valid</errorDescription>
</error>
<error>
<errorCode>E1001</errorCode>
<errorDescription>Postcode AA9 0AA invalid</errorDescription>
</error>
</errors>
<warnings xmlns="http://www.royalmailgroup.com/integration/core/V1">
<warning>
<warningCode>W0036</warningCode>
<warningDescription>E-mail option not selected so e-mail address will be ignored</warningDescription>
</warning>
<warning>
<warningCode>W0035</warningCode>
<warningDescription>SMS option not selected so Telephone Number will be ignored</warningDescription>
</warning>
</warnings>
</integrationFooter>
</createShipmentResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
i am using this method to serialize this response :
Private Sub SerializeCollection(filename As String)
Dim Emps As createShipmentResponse = New createShipmentResponse()
' Note that only the collection is serialized -- not the
' CollectionName or any other public property of the class.
Dim x As XmlSerializer = New XmlSerializer(GetType(createShipmentResponse))
Dim writer As TextWriter = New StreamWriter(filename)
x.Serialize(writer, Emps)
writer.Close()
End Sub
but i am having this error : Illegal characters in path
what does that mean ? and how can i fix this ?
Your SerializeCollection() method expects a file path to serialize to a file. You're currently passing the contents of your response which is why it doesn't work.
If you haven't written the method yourself I think you've not found completely what you're looking for.
This is an example of how the method should be called:
SerializeCollection("C:\Users\Vincent\Desktop\Hello.bin") 'The extension doesn't need to be '.bin', but it's an example.
The method has currently no way of getting your response, for that you should add a second parameter.
As I'm not familiar with Soap serialization I'm afraid I cannot help you further.

How to extract individual/child nodes from a KML file in VisualBasic?

I need to be able to extract individual nodes from this file into variables for further manipulation. I'm writing to the console to see what information is being pulled, but I am struggling to pull the name or description.
I can successfully print the entire file. I've tried getting individual nodes using placemark.<name>.Value and placemark.Element("name").Value, the second of which throws a NullReferenceException. Any ideas on how to be able to pull out the name and description in this instance?
Imports System.Xml
Imports System.Xml.Linq 'Visual Studio 2015 tells me this isn't needed
Imports System.Core 'Visual Studio 2015 tells me this isn't needed
Dim file As XDocument = XDocument.Load(filePath)
Dim placemarks As IEnumerable(Of XElement) = From test In file.Root.Elements()
For Each placemark As XElement In placemarks
Console.WriteLine(placemark) 'This works
Console.WriteLine(placemark.<name>.Value) 'This prints an empty line
Console.WriteLine(placemark.Element("description").Value) 'This throws a NullReferenceException
Next
This is the structure
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'>
<Document>
<name>Untitled layer</name>
<Placemark>
<name>Name 1</name>
<description>Description 1</description>
<ExtendedData>
<Data name='Test data one'>
<value>Test data 1</value>
</Data>
</ExtendedData>
<Point>
<coordinates>34725567547</coordinates>
</Point>
</Placemark>
<Placemark>
<name>Name 2</name>
<description>Description 2</description>
<ExtendedData>
<Data name='Test data two'>
<value>Test data 2</value>
</Data>
</ExtendedData>
<Point>
<coordinates>056795763767</coordinates>
</Point>
</Placemark>
If I have understood you correctly, you are trying to fetch the name & description present inside the PlaceMark node. But, since you are only fetching Root.Elements() your query will only fetch the complete XML starting from your root node.
You need to find the Descendants of PlaceMark node because you need to fetch the name & description inside it. Also, since the root node kml consists of namespace you need to specify that as well.
Here is the code:-
Dim ns As XNamespace = "http://www.opengis.net/kml/2.2"
Dim placeMarks = From test In file.Root.Element(ns + "Document")
.Descendants(ns + "Placemark") Select test
For Each pm In placeMarks
Console.WriteLine("Name: {0}", pm.Element(ns + "name").Value)
Console.WriteLine("Description: {0}", pm.Element(ns + "description").Value)
Console.WriteLine()
Next
I am getting following output:-

Facing issue while convering json data into xml : mule esb

I tried to convert my json data into xml format. But Only half of data is convert into xml.
My payload is
{"orders":[{"orderName":"Laptop","price":34000,"Date":"2014/01/12","Type":"DELL","stock":52,"code":"152666AS"},
{"orderName":"Chip","price":345,"Date":"2014/02/20","Type":"DELL","stock":50,"code":"152666AW"},
{"orderName":"Laptop1","price":35000,"Date":"2015/02/13","Type":"DELL1","stock":51,"code":"152666AX"}]}
But in output I got only one json item
<?xml version='1.0'?>
<orders>
<orderName>Laptop</orderName>
<price>34000</price>
<Date>2014/01/12</Date>
<Type>DELL</Type>
<stock>52</stock>
<code>152666AW</code>
</orders>
My flow is as follow
<flow name="testFlow">
<http:listener config-ref="HTTP_Quickbook" path="/" doc:name="HTTP"/>
<connector-test:my-processor config-ref="ConnectorTest__Configuration_type_strategy" content="APP" doc:name="ConnectorTest"/>
<json:json-to-xml-transformer mimeType="application/json" doc:name="JSON to XML"/>
<logger message="#[payload]" level="INFO" doc:name="Logger"/>
</flow>
I need whole json string in xml format . What I have to change?
I tested with creating custom transformer.. My custom transformer is as follow
InputStream input = new FileInputStream(new File("test.json"));
OutputStream output = System.out;
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
inputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
XMLEventReader reader = inputFactory.createXMLEventReader(input);
XMLOutputFactory outputFactory = new JsonXMLOutputFactory();
outputFactory.setProperty(JsonXMLOutputFactory.PROP_PRETTY_PRINT, true);
XMLEventWriter writer = outputFactory.createXMLEventWriter(output);
writer = new XMLMultipleEventWriter(writer, false,"/orders");
writer.add(reader);
reader.close();
writer.close();
Now I got following error
com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character '{' (code 123) in prolog; expected '<'
at [row,col {unknown-source}]: [1,1]
How to solve this?
i can suggest you one thing to make your requirement to work.
if you are want to generate the xml from json.
do the below
add set-payload component to you flow explicitly specify the value as
{"root":#[payload]}
it will work and i could able to generate the xml data out of the sample data you pasted.
please do try and post your status
Your issue comes from the transformation of the array of orders that fails and returns only one entry.
Behind the scene, the json:json-to-xml-transformer uses Staxon for XML to JSON transformation. Here is the doc on array transformation in Staxon: https://github.com/beckchr/staxon/wiki/Mastering-Arrays
We can see in the Mule source that PROP_MULTIPLE_PI is false and PROP_AUTO_ARRAY is not set to true, therefore only one item of the array is considered, the others are dropped.
So the best is for you to write your own transformer either using Staxon too, configured with the array handling settings you want, or using Groovy XML Markup builder to generate the XML in a nice and easy way.
For what you're looking for json
{
"ocs:price": {
"#exponent": "-1",
"#text": "2"
}
}
That's the format to convert for example that from JSON to XML like this :
<ocs:price exponent="-1">2</ocs:price>
In java/groovy script I used something like this to convert it
import net.sf.json.JSON
import net.sf.json.JSONSerializer
import net.sf.json.xml.XMLSerializer
String str = '''{
"ocs:price": {
"#exponent": "-1",
"#text": "2"
}
}'''
JSON json = JSONSerializer.toJSON( str )
XMLSerializer xmlSerializer = new XMLSerializer()
xmlSerializer.setTypeHintsCompatibility( false )
String xml = xmlSerializer.write( json )
System.out.println(xml)

xpath filter on attribute text

Hi I have an xml file like below,
<Pods>
<item>
<URL>data/_data/2014/09/11/pods/10057-1837887-2965978-0.pdf</URL>
<RunDate>11/09/2014</RunDate>
<DateSigned>11/09/2014 09:13:49
</DateSigned>
</item>
<item>
<URL>data/_data/2014/09/11/pods/10057-0-2965978-0-scan.pdf</URL>
<DateSigned>Not signed</DateSigned>
</item>
</Pods>
I would like to get the conents of the <URL> where <DateSigned> is not equal to "Not Signed"
I have tried
Dim URLNode As XmlNodeList = doc.SelectNodes("//ITEM[DateSigned=Not Signed]/URL")
but this says invalid token I am unsure what I have dine wrong.
Thanks for any help
You need to simply wrap Not signed within single-quotes to make it recognized as string value. Also, XML is case-sensitive, use the correct cases :
Dim URLNode As XmlNodeList = _
doc.SelectNodes("//item[DateSigned='Not signed']/URL")
or if you really meant to get <item> where <DateSigned> is not equals Not signed :
Dim URLNode As XmlNodeList = _
doc.SelectNodes("//item[DateSigned != 'Not signed']/URL")

Read an XML node in namespace using Linq

How do I work out what the namespace declaration is for the Extension node?
I want to return all of the child nodes under: GPO->User->ExtensionData->Extension
<?xml version="1.0" encoding="utf-16"?>
<GPO xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.microsoft.com/GroupPolicy/Settings">
<User>
<VersionDirectory>4</VersionDirectory>
<VersionSysvol>4</VersionSysvol>
<Enabled>true</Enabled>
<ExtensionData>
<Extension xmlns:q1="http://www.microsoft.com/GroupPolicy/Settings/Scripts" xsi:type="q1:Scripts">
<q1:Script>
<q1:Command>Logon.cmd</q1:Command>
<q1:Type>Logon</q1:Type>
<q1:Order>0</q1:Order>
<q1:RunOrder>PSNotConfigured</q1:RunOrder>
</q1:Script>
</Extension>
<Name>Scripts</Name>
</ExtensionData>
</User>
<LinksTo>
<SOMName>an interesting data value</SOMName>
<SOMPath>some data value</SOMPath>
<Enabled>true</Enabled>
<NoOverride>false</NoOverride>
</LinksTo>
</GPO>
This is my attempt:
Dim NS As XNamespace = "http://www.microsoft.com/GroupPolicy/Settings/Scripts"
Dim UserPolCount = XDoc.Descendants(NS + "Extension").First()
I get the following error: Sequence contains no elements
Also, the XML sample I have provided is only a small snippet, the ExtensionData->Extension nodes can be nested in different areas, so I was hoping to find the way of specifying the full path.
Thanks
The Extension Element is still under the root namespace of:
http://www.microsoft.com/GroupPolicy/Settings
Elements under Extension are under the Scripts namespace:
http://www.microsoft.com/GroupPolicy/Settings/Scripts
So you need:
Dim NS As XNamespace = "http://www.microsoft.com/GroupPolicy/Settings/"
Dim NS1 As XNamespace = "http://www.microsoft.com/GroupPolicy/Settings/Scipts"
Dim UserPolCount = XDoc.Descendants(NS + "Extension").First()
Dim ScriptNode = UserPolCount.Elements(NS1 + "Script")
EDIT From the comments:
Dim extension =
XDoc
.Root
.Element(NS + "User")
.Element(NS + "ExtensionData")
.Element(NS + "Extension");
You are using the wrong namespace. You need to use http://www.microsoft.com/GroupPolicy/Settings as the namespace.
The reason is that only the children of Extension are in the Scripts namespace. You can easily see this: The children are all prefixed with q1, the Extension tag itself not. Therefore it is defined in the default namespace, defined by the attribute xmlns="http://www.microsoft.com/GroupPolicy/Settings" on the root tag GPO.