Edit an element inside cdata - c#

I'm trying to edit an element in the following xml, but I'm not sure how to deal with the cdata code... the element I want to edit is FileID
<Import>
<MethodParameters>
<messageXml><![CDATA[
<Message>
<ImportRequest Entity="Users">
<File Name="XXXXXX" Type="Xml" FileID="TestM-00" TotalPartialFiles="1" PartialSequence="1" Md5="">
<![CDATA[
<ImportUserList>
<ImportUser UserName="TestM01" FirstName="TestM01" MiddleName="TestM01" LastName="TestM01" Active="true" Email="TestM01#gmail.com" ExternalId="TestM01"/>
<ImportUser UserName="TestM02" FirstName="TestM02" MiddleName="TestM02" LastName="TestM02" Active="true" Email="TestM02#gmail.com" ExternalId="TestM02"/>
</ImportUserList>
]]]]><![CDATA[>
</File >
</ImportRequest>
</Message>
]]></messageXml>
</MethodParameters>
</Import>
I have something like this in C#, but I'm not sure how to update the Users.xml file, because I know that AdminNode is in the second document
var doc = new XmlDocument();
doc.Load("E:\\Users.xml");
XmlNode node = doc.SelectSingleNode("/Import/MethodParameters/messageXml").FirstChild;
string newID = Guid.NewGuid().ToString();
XmlNodeList xmlRootNode = doc.GetElementsByTagName("messageXml");
String Sxml = xmlRootNode.Item(0).InnerText;
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(Sxml);
XmlNodeList AdminNode = xdoc.GetElementsByTagName("Message");
AdminNode.Item(0).SelectSingleNode("//ImportRequest/File/#FileID").Value = newID;
doc.Save("E:\\Users.xml");

The following code should do the trick:
string xml = #"<Import>
<MethodParameters>
<messageXml><![CDATA[
<Message>
<ImportRequest Entity=""Users"">
<File Name=""XXXXXX"" Type=""Xml"" FileID=""TestM-00"" TotalPartialFiles=""1"" PartialSequence=""1"" Md5="""">
<![CDATA[
<ImportUserList>
<ImportUser UserName=""TestM01"" FirstName=""TestM01"" MiddleName=""TestM01"" LastName=""TestM01"" Active=""true"" Email=""TestM01#gmail.com"" ExternalId=""TestM01""/>
<ImportUser UserName=""TestM02"" FirstName=""TestM02"" MiddleName=""TestM02"" LastName=""TestM02"" Active=""true"" Email=""TestM02#gmail.com"" ExternalId=""TestM02""/>
</ImportUserList>
]]]]><![CDATA[>
</File>
</ImportRequest>
</Message>
]]></messageXml>
</MethodParameters>
</Import>";
var newID = Guid.NewGuid().ToString();
var xDoc = XDocument.Parse(xml);
var messageNode = xDoc.XPathSelectElement(".//messageXml");
var innerDoc = XDocument.Parse(messageNode.Value);
innerDoc.XPathSelectElement(".//ImportRequest/File").Attribute("FileID").Value = newID;
messageNode.ReplaceAll(new XCData(innerDoc.ToString()));
It's pretty dirty now, but at least it produces the expected output:
<Import>
<MethodParameters>
<messageXml><![CDATA[<Message>
<ImportRequest Entity="Users">
<File Name="XXXXXX" Type="Xml" FileID="609bead3-3295-4d68-a07f-1ee47db756fd" TotalPartialFiles="1" PartialSequence="1" Md5="">
<![CDATA[
<ImportUserList>
<ImportUser UserName="TestM01" FirstName="TestM01" MiddleName="TestM01" LastName="TestM01" Active="true" Email="TestM01#gmail.com" ExternalId="TestM01"/>
<ImportUser UserName="TestM02" FirstName="TestM02" MiddleName="TestM02" LastName="TestM02" Active="true" Email="TestM02#gmail.com" ExternalId="TestM02"/>
</ImportUserList>
]]]]><![CDATA[>
</File>
</ImportRequest>
</Message>]]></messageXml>
</MethodParameters>
</Import>

Related

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
}
}

Generate XML for <GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope">

Please help me I want generate, using C#, root XML for send to the server.
For similar
<?xml version="1.0" encoding="utf-8"?>
<GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope">
<EnvelopeVersion>2.0</EnvelopeVersion>
<Header>
<MessageDetails>
<Class>SendDocument</Class>
<Qualifier>request</Qualifier>
<Function>submit</Function>
<TransactionID>5</TransactionID>
<CorrelationID></CorrelationID>
</MessageDetails>
<SenderDetails>
<IDAuthentication>
<SenderID>[USER]</SenderID>
<Authentication>
<Method>clear</Method>
<Value>[PASS]</Value>
</Authentication>
</IDAuthentication>
</SenderDetails>
</Header>
<Body>
<Message xmlns="urn:g3.ge:dea:call:SendDocument:v1">
................
</Message>
</Body>
</GovTalkMessage>
Beforehand thanks for answer
First of all, you'll need to generate XSD schemas for your XML. The Government Gateway should provide XSDs for your particular submission domain. If not, you can generate a reasonably good schema from the XML file by using the Visual Studio XML tools under Create Schema from the XML menu.
Once you have a schema file you can use the XSD.exe tool from the Windows SDK to generate service classes. If you have multiple schema files (say, one for the GovTalkMessage wrapper and one for a particular domain, like Inland Revenue in my example below) you can combine them in one service class file:
If the XSD tool is installed in its typical location you can run this command:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\x64>xsd.exe /c c:\Schemas\GovTalkMessage.xsd C:\ServiceClasses\IREnvelope.xsd /o:C:\GovTalkApplication
Once you have service classes for your XML you can create new objects from your data and serialize them into XML fairly easily. In this code sample I have used AppSettings in the configuration file to store various constant values and a private DataTable called _localData to hold my body data which I am putting into an IR R68 payload (in the element). I am also using a log4net logger here, which is incidental. The CreateIRBody method is something you will have to write for whatever payload you need to include:
public GovTalkMessage CreateRequestMessage(string env)
{
try
{
log.Debug("CreateRequestMessage called");
GovTalkMessageBody Body = new GovTalkMessageBody();
IR68 ir68 = new IR68(_localData);
log.Debug("Creating IR68 body ...");
IRenvelope ire = new IRenvelope();
ire = ir68.CreateIRBody();
//serialize ire into XmlElement and then set Body.Any =
XmlElement xe = GiftAidSubmissionProcessController.SerializeIREnvelope(ire);
XmlElement[] XmlElementIRenvelope = new XmlElement[1];
XmlElementIRenvelope[0] = xe;
Body.Any = XmlElementIRenvelope;
//GovTalkDetails
GovTalkMessageGovTalkDetailsChannelRoutingChannel Channel = new GovTalkMessageGovTalkDetailsChannelRoutingChannel();
Channel.Version = ConfigurationManager.AppSettings["ChannelVersion"];
Channel.Product = ConfigurationManager.AppSettings["ChannelProduct"];
Channel.ItemElementName = ItemChoiceType.URI;
Channel.Item = ConfigurationManager.AppSettings["ChannelURI"];
GovTalkMessageGovTalkDetailsChannelRouting ChannelRouting = new GovTalkMessageGovTalkDetailsChannelRouting();
ChannelRouting.Channel = Channel;
GovTalkMessageGovTalkDetailsKey Key = new GovTalkMessageGovTalkDetailsKey();
Key.Type = ConfigurationManager.AppSettings["GovTalkDetailsKeyType"];
Key.Value = ConfigurationManager.AppSettings["GovTalkDetailsKey"];
GovTalkMessageGovTalkDetails Details = new GovTalkMessageGovTalkDetails();
GovTalkMessageGovTalkDetailsChannelRouting[] ChannelRoutings =
new GovTalkMessageGovTalkDetailsChannelRouting[1];
ChannelRoutings[0] = ChannelRouting;
Details.ChannelRouting = ChannelRoutings;
GovTalkMessageGovTalkDetailsKey[] Keys = new GovTalkMessageGovTalkDetailsKey[1];
Keys[0] = Key;
Details.Keys = Keys;
string[] TargetDetails = new string[1];
TargetDetails[0] = ConfigurationManager.AppSettings["GovTalkDetailsTargetOrganistion"];
Details.TargetDetails = TargetDetails;
//GovTalk Header
GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication Authentication = new GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication();
switch (ConfigurationManager.AppSettings["SenderAuthenticationMethod"])
{
case "MD5":
Authentication.Method = GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthenticationMethod.MD5;
break;
case "clear":
Authentication.Method = GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthenticationMethod.clear;
break;
case "W3Csigned":
Authentication.Method = GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthenticationMethod.W3Csigned;
break;
}
Authentication.Role = ConfigurationManager.AppSettings["SenderAuthenticationRole"];
Authentication.Item = ConfigurationManager.AppSettings["SenderAuthenticationValue"];
GovTalkMessageHeaderSenderDetailsIDAuthentication IDAuthentication = new GovTalkMessageHeaderSenderDetailsIDAuthentication();
IDAuthentication.SenderID = ConfigurationManager.AppSettings["SenderID"];
GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication[] Authentications = new GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication[1];
Authentications[0] = Authentication;
IDAuthentication.Authentication = Authentications;
GovTalkMessageHeaderSenderDetails SenderDetails = new GovTalkMessageHeaderSenderDetails();
SenderDetails.IDAuthentication = IDAuthentication;
GovTalkMessageHeaderMessageDetails MessageDetails = new GovTalkMessageHeaderMessageDetails();
MessageDetails.Class = ConfigurationManager.AppSettings["MessageDetailsClass"];
MessageDetails.Qualifier = GovTalkMessageHeaderMessageDetailsQualifier.request;
MessageDetails.FunctionSpecified = true;
MessageDetails.Function = GovTalkMessageHeaderMessageDetailsFunction.submit;
MessageDetails.TransformationSpecified = true;
MessageDetails.Transformation = GovTalkMessageHeaderMessageDetailsTransformation.XML;
MessageDetails.GatewayTest = ConfigurationManager.AppSettings["MessageDetailsGatewayTest"];
if (env == "local")
{
MessageDetails.GatewayTimestampSpecified = true;
MessageDetails.GatewayTimestamp = DateTime.Now;
}
else
{
MessageDetails.GatewayTimestampSpecified = false;
MessageDetails.GatewayTimestamp = DateTime.MinValue; }
GovTalkMessageHeader Header = new GovTalkMessageHeader();
Header.MessageDetails = MessageDetails;
Header.SenderDetails = SenderDetails;
GovTalkMessage GovTalkMessage = new hmrcclasses.GovTalkMessage();
GovTalkMessage.EnvelopeVersion = ConfigurationManager.AppSettings["GovTalkMessageEnvelopeVersion"];
GovTalkMessage.Header = Header;
GovTalkMessage.GovTalkDetails = Details;
GovTalkMessage.Body = Body;
log.Info("GovTalkMessage created successfully");
return GovTalkMessage;
}
catch (Exception ex)
{
log.Error(ex);
throw;
}
}
Hope this helps you get started.
Copy whole XML (CRTL+A CTRL+C)
Open Visual Studio and create new Class
Click menu - Edit -> Paste Special -> Paste XML As Classes
after that you can use XmlSerializer to generate that XML
var entity = new GovTalkMessage();
//fill entity properties with data
var writer = new StringWriter();
var serializer = new XmlSerializer(typeof(GovTalkMessage));
serializer.Serialize(writer, entity);
var xmlText = writer.ToString();
//and so on...
This is a whole XML file.
<?xml version="1.0" encoding="utf-8"?>
<GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope">
<EnvelopeVersion>2.0</EnvelopeVersion>
<Header>
<MessageDetails>
<Class>SendDocument</Class>
<Qualifier>request</Qualifier>
<Function>submit</Function>
<CorrelationID></CorrelationID>
</MessageDetails>
<SenderDetails>
<IDAuthentication>
<SenderID>[USER]</SenderID>
<Authentication>
<Method>clear</Method>
<Value>[PASS]</Value>
</Authentication>
</IDAuthentication>
</SenderDetails>
</Header>
<Body>
<Message xmlns="urn:g3.ge:dea:call:SendDocument:v1">
<Container xmlns="http://www.dea.gov.ge/schemas/2011/dx">
<Reference>GUID</Reference>
<DocDate>yyyy-MM-dd HH:mm:ss</DocDate>
<DocNumber>string</DocNumber>
<Persons>
<Person>
<OriginID>1</OriginID>
<FirstName>string</FirstName>
<LastName>string</LastName>
<Position>string</Position>
<PersonType>1</PersonType>
<ResolutionText>string (max length: 1000 chars)</ResolutionText>
<OrgUnit>string (max length: 4000 chars)</OrgUnit>
</Person>
<Person>
<OriginID>447</OriginID>
<FirstName>string</FirstName>
<LastName>string</LastName>
<Position>string</Position>
<PersonType>2</PersonType>
<ResolutionText>string (max length: 1000 chars)</ResolutionText>
<OrgUnit>string (max length: 4000 chars)</OrgUnit>
</Person>
</Persons>
<Subject>string</Subject>
<MainDoc>
<Doc>
<FileName></FileName>
<ContentType></ContentType>
<Signature>
<Type></Type>
<Data>BASE64BINARY</Data>
</Signature>
<Data>BASE64BINARY</Data>
<DocType></DocType>
</Doc>
</MainDoc>
<RespondTo>
<OriginalDoc>
<Reference>GUID</Reference>
<Type/>
</OriginalDoc>
</RespondTo>
<OriginalReference>GUID</OriginalReference>
<AttachedDocs>
<Doc>
<FileName></FileName>
<ContentType></ContentType>
<Signature>
<Type></Type>
<Data>BASE64BINARY</Data>
</Signature>
<Data>BASE64BINARY</Data>
<DocType></DocType>
</Doc>
<Doc>
<FileName></FileName>
<ContentType></ContentType>
<Signature>
<Type></Type>
<Data>BASE64BINARY</Data>
</Signature>
<Data>BASE64BINARY</Data>
<DocType></DocType>
</Doc>
<Doc>
<FileName></FileName>
<ContentType></ContentType>
<Signature>
<Type></Type>
<Data>BASE64BINARY</Data>
</Signature>
<Data>BASE64BINARY</Data>
<DocType></DocType>
</Doc>
</AttachedDocs>
<Signature>
<Type></Type>
<Data>BASE64BINARY</Data>
</Signature>
</Container>
</Message>
</Body>
</GovTalkMessage>

Extraction of Values from Xml SOAP response in 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">

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?

Categories

Resources