How to change a value of an attribute? - c#

in the last days i tried to change a value of a single attribute of this application File
The Xml-File:
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly xsi:schemaLocation="urn:schemas-microsoft-com:asm.v1 assembly.adaptive.xsd"
manifestVersion="1.0" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1"
xmlns="urn:schemas-microsoft-com:asm.v2"
xmlns:asmv2="urn:schemas-microsoft-com:asm.v2"
xmlns:xrml="urn:mpeg:mpeg21:2003:01-REL-R-NS"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:asmv3="urn:schemas-microsoft-com:asm.v3"
xmlns:dsig="http://www.w3.org/2000/09/xmldsig#"
xmlns:co.v1="urn:schemas-microsoft-com:clickonce.v1"
xmlns:co.v2="urn:schemas-microsoft-com:clickonce.v2">
<assemblyIdentity name="lolz" version="1.1.1.1" publicKeyToken="12345" language="neutral" processorArchitecture="x86" xmlns="urn:schemas-microsoft-com:asm.v1" />
<description asmv2:publisher="Example" asmv2:product="Productexample2" asmv2:supportUrl="Example" xmlns="urn:schemas-microsoft-com:asm.v1" />
<deployment install="true" mapFileExtensions="true" minimumRequiredVersion="1.1.1.1" trustURLParameters="true">
<subscription>
<update>
<beforeApplicationStartup />
</update>
</subscription>
<deploymentProvider codebase="http://Test" />
</deployment>
</asmv1:assembly>
Here i try to change the value of
<description asmv2:product = "Productexample">
into
<description asmv2:product = "Productexample2">
,and the value of
<deploymentProvider codebase="http://Test" />
into
<deploymentProvider codebase="http://Test2" />
Currently i tried :
private void changeAttribute (string xmlPath)
{
string newValue = "Productexample2";
XmlDocument xmlDoc= new XmlDocument();
xmlDoc.Load(xmlPath);
XmlNode node = xmlDoc.SelectSingleNode("asmv1:assembly/description/asmv2:product");
node.Attributes[0].Value = newValue;
xmlDoc.Save(xmlPath);
}
But it throws the Exception 'An unhandled exception of type 'System.Xml.XPath.XPathException' occurred in System.Xml.dll' so i think asmv1:assembly/description/asmv2:product is wrong ...
any suggestions of code?
as always you can correct me in any way :)

You have to use a namespace manager to make the prefixes work and you need the # character to indicate it is an attribute you are referencing.
So this should work:
XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable);
manager.AddNamespace("asmv1", "urn:schemas-microsoft-com:asm.v1");
manager.AddNamespace("asmv2", "urn:schemas-microsoft-com:asm.v2");
XmlNode node = xmlDoc.SelectSingleNode("/asmv1:assembly/asmv1:description/#asmv2:product", manager);
Also, your first line in the XML root is incomplete. It should be:
<asmv1:assembly xsi:schemaLocation="urn:schemas-microsoft-com:asm.v1 assembly.adaptive.xsd"
manifestVersion="1.0"
xmlns:asmv1="urn:schemas-microsoft-com:asm.v1"
xmlns="urn:schemas-microsoft-com:asm.v2"
xmlns:asmv2="urn:schemas-microsoft-com:asm.v2"
xmlns:xrml="urn:mpeg:mpeg21:2003:01-REL-R-NS"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:asmv3="urn:schemas-microsoft-com:asm.v3"
xmlns:dsig="http://www.w3.org/2000/09/xmldsig#"
xmlns:co.v1="urn:schemas-microsoft-com:clickonce.v1"
xmlns:co.v2="urn:schemas-microsoft-com:clickonce.v2"
>

Related

Loop XML file and add to List c#

I have this XML file:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfPasswordSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<PasswordSettings>
<CustomerRef>c</CustomerRef>
<Node>n</Node>
<Name>na</Name>
<Login>l</Login>
<Password>ITra+Map1RxklmcSY5yOo9wU9tUV0S4C4qwUv4p2ZFS3L8ByJYXmA9YjswlSTjQZXUJAkV3Z6mhY8OF5/dFOLNAZZRk2i2IOzrVOWSDfdpB8/Vm7PPF0ucSHILHNWpT8</Password>
<FileType>ft</FileType>
</PasswordSettings>
<PasswordSettings>
<CustomerRef>c</CustomerRef>
<Node>n</Node>
<Name>na</Name>
<Login>l</Login>
<Password>ITra+Map1RxklmcSY5yOo9wU9tUV0S4C4qwUv4p2ZFS3L8ByJYXmA9YjswlSTjQZXUJAkV3Z6mhY8OF5/dFOLNAZZRk2i2IOzrVOWSDfdpB8/Vm7PPF0ucSHILHNWpT8</Password>
<FileType>ft</FileType>
</PasswordSettings>
</ArrayOfPasswordSettings>
As you see there are multiple <PasswordSettings> which is a list of multiple items like name, login and password. Can I iterate the <PasswordSettings> in some foreach <PasswordSettings> loop and get the elements?
Please try with this example :
XML:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
<Brand name="Brand1">
<product name="Product1" />
<product name="Product2" />
</Brand>
<Brand name="Brand2">
<product name="Product3" />
<product name="Product4" />
</Brand>
</root>
C#:
StringBuilder result = new StringBuilder();
foreach (XElement level1Element in XElement.Load(#"D:\product.xml").Elements("Brand"))
{
result.AppendLine(level1Element.Attribute("name").Value);
foreach (XElement level2Element in level1Element.Elements("product"))
{
result.AppendLine(" " + level2Element.Attribute("name").Value);
}
}
Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication108
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var results = doc.Descendants("PasswordSettings").Select(x => new
{
c = (string)x.Element("CustomerRef"),
node = (string)x.Element("Node"),
name = (string)x.Element("Name"),
login = (string)x.Element("Login"),
password = (string)x.Element("Password"),
fileType = (string)x.Element("FileType")
}).ToList();
}
}
}

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

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

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