Extraction of Values from Xml SOAP response in C# - c#

I am trying to write down a code to read a SOAP Response message and extract values without success.
I am trying to extract scalar values starting at the "structure" node.
Here is my code:
//Extracting the xml http message.
xmlDoc.LoadXml(xmlHttp.responseText);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ns", "http://messages.ara.algorithmics.com");
nsmgr.AddNamespace("ns2", "http://ws.ara.algorithmics.com");
XmlElement root = xmlDoc.DocumentElement;
XmlNode root1 = root.SelectSingleNode("//structure", nsmgr);
The message is looking like this:
<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<getStructureStatelessResponse xmlns="http://ws.ara.algorithmics.com" xmlns:ns2="http://messages.ara.algorithmics.com">
<contextId>Interactive_CWMAdmin20140828134101_BASE</contextId>
<userId>CWMAdminSimulation_10267</userId>
<parameters>
<aggregation>a:flat</aggregation>
<currency>c:usd</currency>
<depth>2</depth>
<path requestedValue="portfolio://All%20Portfolios/GROUP">portfolio://actual/GROUP</path>
</parameters>
<outputDefs>
<outputDef definitionId="od0">
<outputId>o:Price</outputId>
<annualized>false</annualized>
<currency>c:usd</currency>
<nominalfx>false</nominalfx>
</outputDef>
<outputDef definitionId="od1">
<outputId>o:Value</outputId>
<annualized>false</annualized>
<currency>c:usd</currency>
<nominalfx>false</nominalfx>
</outputDef>
<outputDef definitionId="od2">
<outputId>o:UnitDirtyPrice</outputId>
<annualized>false</annualized>
<currency>c:usd</currency>
<nominalfx>false</nominalfx>
</outputDef>
</outputDefs>
<structure>
<port childCount="316" expandedNodeName="Position View" name="Position View" nodeId="669">
<outputResults>
<scalar ref="od0" value="1.890480805674964E7"/>
<scalar ref="od1" value="1.890480805674964E7"/>
<ratio ref="od2" value="NaN"/></outputResults>
<pos locked="true" name="CF_IF Asset#SPL_ASE#Annuitant mortality improves" nodeId="347" secId="CF_IF Asset#SPL_ASE#Annuitant mortality improves">
<outputResults>
<scalar ref="od0" value="0.0"/><scalar ref="od1" value="0.0"/>
<ratio ref="od2" value="0.0"/></outputResults>
</pos>
<pos locked="true" name="CF_IF Asset#SPL_ASE#Assured lives mortality increases" nodeId="359" secId="CF_IF Asset#SPL_ASE#Assured lives mortality increases">

Related

I'm getting an xpath error when navigating to an element in the soap message

Programming Langauge - c#.
Below mentioned error is showing.
Unhandled Exception: System.Xml.XPath.XPathException: Namespace Manager or XsltC
ontext needed. This query has a prefix, variable, or user-defined function.
This is the code that I wrote to return the inner text.
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(#"C:\test\myfile.xml");
var nsmgr = new XmlNamespaceManager(xmldoc.NameTable);
nsmgr.AddNamespace("env", "http://schemas.xmlsoap.org/soap/envelope/");
nsmgr.AddNamespace("ns1", "http://sse/ECOM:1.0:schema:messages");
nsmgr.AddNamespace("wsa", "http://www.w3.org/2005/08/addressing");
XmlNode node = xmldoc.SelectsingleNode("/*/env:Body/env:response/env:customerAccountsGrp[1]/env:customerAccountID");
Console.WriteLine(xmldoc.SelectSingleNode("/*/env:Body/env:response/env:customerAccountsGrp[1]/env:customerAccountID").InnerText);
This is the soap message
<env:Envelope
xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:wsa="http://www.w3.org/2005/08/addressing">
<env:Header>
<wsa:MessageID>urn:5C4DCC70E6F411E69F7EF5AAD683B4B3</wsa:MessageID>
<wsa:ReplyTo>
<wsa:Address>http://www.w3.org/2005/08/addressing/anonymous</wsa:Address>
</wsa:ReplyTo><wsa:FaultTo> <wsa:Address>http://www.w3.org/2005/08/addressing/anonymous</wsa:Address>
</wsa:FaultTo>
</env:Header>
<env:Body>
<response
xmlns:ns0="urn:sse:ECOM:1.0:schema:messages"
xmlns="urn:sse:ECOM:1.0:schema:messages">
<ns0:customerAccountsGrp>
<ns0:customerAccountID>1212121212</ns0:customerAccountID>
<ns0:customerAccountStatus>AC</ns0:customerAccountStatus>
<ns0:serviceType>AB</ns0:serviceType>
<ns0:brandCode>XXX </ns0:brandCode>
<ns0:affinityType> </ns0:affinityType>
<ns0:paymentType>VV</ns0:paymentType>
</ns0:customerAccountsGrp><ns0:customerAccountsGrp>
<ns0:customerAccountID>4545454545445</ns0:customerAccountID>
<ns0:customerAccountStatus>BC</ns0:customerAccountStatus>
<ns0:serviceType>FH</ns0:serviceType>
<ns0:brandCode>SE</ns0:brandCode>
<ns0:affinityType></ns0:affinityType>
<ns0:paymentType>NM</ns0:paymentType>
</ns0:customerAccountsGrp>
Can anyone help me on this issue?
Best Regards.

How to read xml element from the following file?

I have the following xml file and I am trying to read name element which I am not able to, any idea how can I read that and other elements ?
<?xml version="1.0" encoding="us-ascii"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>tata</name>
<SSIDConfig>
<SSID>
<name>SampleSingleSignOn</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<autoSwitch>false</autoSwitch>
<MSM>
<security>
<authEncryption>
<authentication>WPA2</authentication>
<encryption>AES</encryption>
<useOneX>true</useOneX>
</authEncryption>
<OneX xmlns="http://www.microsoft.com/networking/OneX/v1">
<cacheUserData>true</cacheUserData>
<maxAuthFailures>3</maxAuthFailures>
<authMode>user</authMode>
<singleSignOn>
<type>preLogon</type>
<maxDelay>10</maxDelay>
</singleSignOn>
<EAPConfig>
<EapHostConfig xmlns="http://www.microsoft.com/provisioning/EapHostConfig"
xmlns:eapCommon="http://www.microsoft.com/provisioning/EapCommon"
xmlns:baseEap="http://www.microsoft.com/provisioning/BaseEapMethodConfig">
<EapMethod>
<eapCommon:Type>25</eapCommon:Type>
<eapCommon:AuthorId>0</eapCommon:AuthorId>
</EapMethod>
<Config xmlns:baseEap="http://www.microsoft.com/provisioning/BaseEapConnectionPropertiesV1"
xmlns:msPeap="http://www.microsoft.com/provisioning/MsPeapConnectionPropertiesV1"
xmlns:msChapV2="http://www.microsoft.com/provisioning/MsChapV2ConnectionPropertiesV1">
<baseEap:Eap>
<baseEap:Type>25</baseEap:Type>
<msPeap:EapType>
<msPeap:ServerValidation>
<msPeap:DisableUserPromptForServerValidation>false</msPeap:DisableUserPromptForServerValidation>
<msPeap:TrustedRootCA />
</msPeap:ServerValidation>
<msPeap:FastReconnect>true</msPeap:FastReconnect>
<msPeap:InnerEapOptional>0</msPeap:InnerEapOptional>
<baseEap:Eap>
<baseEap:Type>26</baseEap:Type>
<msChapV2:EapType>
<msChapV2:UseWinLogonCredentials>true</msChapV2:UseWinLogonCredentials>
</msChapV2:EapType>
</baseEap:Eap>
<msPeap:EnableQuarantineChecks>false</msPeap:EnableQuarantineChecks>
<msPeap:RequireCryptoBinding>false</msPeap:RequireCryptoBinding>
<msPeap:PeapExtensions />
</msPeap:EapType>
</baseEap:Eap>
</Config>
</EapHostConfig>
</EAPConfig>
</OneX>
</security>
</MSM>
</WLANProfile>
And I am reading like this:
XDocument xdoc = XDocument.Load("xmlfile1.xml");
xdoc.Root.Element("name")
it returns null element.
You have to take the XML namespace into account:
XNamespace ns = "http://www.microsoft.com/networking/WLAN/profile/v1";
XElement name = xdoc.Root.Element(ns + "name");

Reading in XML from WPF c#

I'm struggling to read in a "GPX" file to a WPF (c#) project. Sample GPX is provided below. I've tried a number of different options with the same result.
Document is loading ok, but I'm unable to break it down to access the Nodes Directly.
Any help would be greatly appreciated.
Thanks.
private void Simple_Click(object sender, RoutedEventArgs e)
{
XmlDocument xml = new XmlDocument();
xml.Load(#"C:\Users\Jonathon\Desktop\GPX_Data.gpx");
XmlNodeList nodes = xml.SelectNodes("trkpt"); // have tried: double '/' to get nodes at any level (XPath syntax)
//XmlNodeList nodes = xml.SelectNodes("/gpx/trk/trkseg/trkpt");
int count = 0;
foreach (XmlNode xn in nodes)
{
count++;
}
}
}
Sample GPX File
<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Endomondo.com"
xsi:schemaLocation="http://www.topografix.com/GPX/1/1
http://www.topografix.com/GPX/1/1/gpx.xsd
http://www.garmin.com/xmlschemas/GpxExtensions/v3
http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd
http://www.garmin.com/xmlschemas/TrackPointExtension/v1
http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd"
xmlns="http://www.topografix.com/GPX/1/1"
xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1"
xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<metadata>
<author>
<name>Jonathon Ralfe</name>
<email id="jonathon" domain="ralfe.net"/>
</author>
<link href="http://www.endomondo.com">
<text>Endomondo</text>
</link>
<time>2015-01-27T18:31:26Z</time>
</metadata>
<trk>
<src>http://www.endomondo.com/</src>
<link href="https://www.endomondo.com/workouts/463986953/2256850">
<text>endomondo</text>
</link>
<type>SKIING_DOWNHILL</type>
<trkseg>
<trkpt lat="45.576892" lon="6.894079">
<time>2015-01-26T09:49:57Z</time>
</trkpt>
<trkpt lat="45.576892" lon="6.894079">
<ele>1595.0</ele>
<time>2015-01-26T09:49:59Z</time>
</trkpt>
<trkpt lat="45.577109" lon="6.893946">
<ele>1581.0</ele>
<time>2015-01-26T09:51:46Z</time>
</trkpt>
<trkpt lat="45.5772" lon="6.894084">
<ele>1575.0</ele>
<time>2015-01-26T09:52:02Z</time>
</trkpt>
<trkpt lat="45.577247" lon="6.894212">
<ele>1577.0</ele>
<time>2015-01-26T09:52:05Z</time>
</trkpt>
<trkpt lat="45.577317" lon="6.89452">
<ele>1589.0</ele>
<time>2015-01-26T09:52:11Z</time>
</trkpt>
That's because your xml contains namespaces, so you have to set namespace when querying data.
Consider this approach:
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("x", "http://www.topografix.com/GPX/1/1");
XmlNodeList nodes = xml.SelectNodes("//x:trkpt", nsmgr);
Here we're creating NamespaceManager, setting namespace according to your data xmlns="http://www.topografix.com/GPX/1/1" attribute and using this namespace in XPath.
By XPath selection:
foreach(XElement aElement in xml.XPathSelectElements("/trk/trkseg").Elements())
{
foreach(XNode aXNode in aElement.Nodes())
{
//Access subnodes of trkpt
}
}

XmlDocument and getting specific Attributes using xPath

I have seen a couple of examples on here where Xpath is used in conjunction with XmlDocument to get a specific attribute from an XmlDocument Node.... Example
Console.WriteLine(xmlDocument.SelectSingleNode("//dataTemplateSpecification/templates/template/elements/element/#name").Value.ToString());
For some reason I am getting a "Object reference not set to an instance of an object." exception. Whenever I run across that particular line of code. I have a little test app that I have set up to test out different things before I put them into my main project...
Here is the code for that...
namespace ReadXml
{
class Program
{
static void Main(string[] args)
{
//string fulXmlPath = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/templateExample.xml");
XDocument xDocument = XDocument.Load("C:\\Users\\derekww\\Documents\\XML Documents\\templateExample.xml");
XElement elem = xDocument.Element("dataTemplateSpecification"); ;
XmlDocument xmlDocument = new XmlDocument();
StreamReader file = new StreamReader("C:\\Users\\derekww\\Documents\\XML Documents\\templateExample.xml");
xmlDocument.Load(file);
//XmlDocument theDoc = new XmlDocument();
//using (var xmlReader = xDocument.CreateReader())
//{
// xmlDocument.Load(xmlReader);
//}
//Console.WriteLine(elem.ToString());
XmlNode xNode = xmlDocument.SelectSingleNode("//dataTemplateSpecification/templates/template/elements/element");
Console.WriteLine("WORK PLEASE!!!! {0}", xNode.Value.ToString());
//Console.WriteLine(xmlDocument.SelectSingleNode("//dataTemplateSpecification/templates/template/elements/element/#name").Value.ToString());
//Console.WriteLine("This better Work>>>> {0}", xmlDocument.Attributes["/dataTemplateSpecification/templates/template/elements/element/#name"].Value);
Console.ReadLine();
//Console.WriteLine("This better Work>>>> {0}", xmlDocument.SelectSingleNode("//dataTemplateSpecification/templates/template/elements/element/#name").Value);
//foreach (String AttVal in xmlDocument.SelectSingleNode("//dataTemplateSpecification/templates/template/elements/element/#name").Value)
{
//Console.WriteLine("This better Work>>>> {0}", AttVal);
}
}
}
}
Here is part of the XML that I used...
<?xml version="1.0" encoding="utf-8"?>
<dataTemplateSpecification id="id1" name="name1" xmlns="http://EADIS.upmc.com /DataTemplateSpecification.xsd">
<description xmlns="">
<html>text</html>
</description>
<templates xmlns="">
<template>
<elements>
<element id="element0" name="PatientId" display="Patient ID" dataType="String" value="0101010111111" visable="false" readOnly="true">
<validation>
<rules>
<rule id="0" test="#element0.value == ''">
<fail>
<html><b>Patient ID is null, value must be present</b></html>
</fail>
</rule>
</rules>
</validation>
</element>
</elements>
</template>
<templates>
I just showed you the part that you need to understand the xml structure. I assure you that it is well formed. I think I asked this question before but somehow or the other it didn't get posted (maybe I forgot, who knows). Any help with this would be greatly appreciated. If I come up with a reason for why it isn't working I will be sure to let you guys know.
Thank You.
Why can't you use this XPath:
xmlDocument.SelectSingleNode("//templates/template/elements/element/#name").Value
You need to specify the namespace of the XML file in your code.
See here for more info: How to select xml root node when root node has attribute?

Need Help About Using XPathNavigator in C#?

My XML file as below. It mixed schema and normal elements.
<?xml version="1.0" encoding="utf-8"?>
<!-- R1 -->
<ax:root xmlns:ax="http://amecn/software/realtime/ax">
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="EquipmentConstants">
<xsd:complexType>
<xsd:sequence>
<xsd:element minOccurs="0" maxOccurs="unbounded" ref="EquipmentConstant" />
</xsd:sequence>
</xsd:complexType>
<xsd:unique name="id">
<xsd:selector xpath=".//EquipmentConstant" />
<xsd:field xpath="#id" />
</xsd:unique>
</xsd:element>
......
......
</xsd:schema>
<EquipmentConstants xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<EquipmentConstant id="0">
<Name>SerialNumber</Name>
<Group>SYSTEM</Group>
<Data>
<Value min="0" max="10000000" scale_factor="0" unit="U_NO_UNITS" permission="NolimitedAndNoChangeable" type="xsd_string" enum="" flag="0">0</Value>
</Data>
<Description>Serial Number</Description>
</EquipmentConstant>
.....
.....
</EquipmentConstants>
</ax:root>
My C# code as below. I want to loop the elements start from (by pass all the content of schema)
<EquipmentConstants xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
XPathDocument doc = new XPathDocument("test.xml");
XPathNavigator navigator = doc.CreateNavigator();
navigator.MoveToRoot(); // <?xml version="1.0" encoding="utf-8"?>
//navigator.MoveToFirstChild(); // <!-- R1 -->
// 1st, I tried to use MoveToChield(), But I failed to move there.
navigator.MoveToChild("EquipmentConstants");
// Then, I also tried to use SelectSingleNode(). But I failed too.
navigator.SelectSingleNode("ax/EquipmentConstants");
while (navigator.MoveToNext())
{
// do something.
}
Could you please give me some suggestion. Thank you.
XPathNavigator navigator = doc.CreateNavigator();
if (navigator == null)
{
return;
}
foreach (XPathNavigator nav in
navigator.Select("/" + "EquipmentConstants" + "/" + "EquipmentConstant"))
{
}
My solution as below.
XPathDocument doc = new XPathDocument("test.xml");
XPathNavigator navigator = doc.CreateNavigator();
navigator.MoveToRoot(); // <?xml version="1.0" encoding="utf-8"?>
navigator.MoveToFirstChild(); // <!-- R1 -->
navigator.MoveToNext(); // <ax:root xmlns:ax="http://amecn/software/realtime/ax">
navigator.MoveToChild("EquipmentConstants", ""); // <EquipmentConstants xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
navigator.MoveToFirstChild(); // <EquipmentConstant id="0">
do
{
// Loop body;
} while (navigator.MoveToNext());

Categories

Resources