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");
Related
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>
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
}
}
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">
I've been trying to select some XML comments like so:
XDocument doc = XDocument.Load(args[0]);
var comments = from node in doc.Elements().DescendantNodesAndSelf()
where node.NodeType == XmlNodeType.Comment
select node as XComment;
With this solution I'm getting all xml comment of the file, but I want to select only those comments and create XElement with it:
<Connections>
...
<!-- START Individual Account Authentication -->
<!--<authentication mode="None"/>
<roleManager enabled="false"/>
<profile enabled="false"/>-->
<!-- END Individual Account Authentication -->
...
</Connections>
Any solutions ? :S
Here is a sample:
XDocument doc = XDocument.Load("input.xml");
foreach (XComment start in doc.DescendantNodes().OfType<XComment>().Where(c => c.Value.StartsWith(" START")).ToList())
{
XComment end = start.NodesAfterSelf().OfType<XComment>().FirstOrDefault(c => c.Value.StartsWith(" END"));
if (end != null)
{
foreach (XComment comment in end.NodesBeforeSelf().OfType<XComment>().Intersect(start.NodesAfterSelf().OfType<XComment>()).ToList())
{
comment.ReplaceWith(XElement.Parse("<dummy>" + comment.Value + "</dummy>").Nodes());
}
// if wanted/needed
start.Remove();
end.Remove();
}
}
doc.Save("output.xml");
That gives me
<Connections>
...
<authentication mode="None" /><roleManager enabled="false" /><profile enabled="false" />
...
</Connections>
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?