Unable to Read XML using C# and XmlDocument - c#

I would like to read a XML File with C#, but i always get an error.
This is my XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<OMDS xmlns="urn:omds20" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:omds20 ./omds26-00.xsd">
<PAKET VUNr="014" PaketZpktErstell="2014-08-29T10:45:08.575" PaketZpktLetztErstell="2014-08-29T10:45:08.575" PaketInhCd="VM" PaketUmfCd="G" VUVersion="26-00" DVRNrAbs="0">
<PERSON ....
<PERSON ....
<PERSON ....
I would like to read this XML, but XMLContentNodes is always null. So i am unable to get the SelectSingleNode with this Path, but i cant find out what should be wrong here?
XmlDocument doc = new XmlDocument();
doc.Load(openFileDialog1.FileName);
XmlNode XMLContentNodes = doc.SelectSingleNode("/OMDS/PAKET"); // Error Here
XmlNodeList PersonNodeList = XMLContentNodes.SelectNodes("PERSON");
foreach (XmlNode node in PersonNodeList)
{
.....
Any help would be greatly appreciated.

The usual namespace problem. Try
XmlNamespaceManager mgr = new XmlNamespaceManager(new NameTable());
mgr.AddNamespace("d", "urn:omds20");
XmlNode XMLContentNodes = doc.SelectSingleNode("/d:OMDS/d:PAKET", mgr);
XmlNodeList PersonNodeList = XMLContentNodes.SelectNodes("d:PERSON", mgr);

You'll need to add the namespace urn:omds20 to the doc XmlDocument object after loading your XML file in it. It will look like the following:
XmlDocument doc = new XmlDocument();
doc.Load(openFileDialog1.FileName);
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(doc.NameTable);
xmlnsManager.AddNamespace("omds20", "urn:omds20");
Then you can query for the PAKET node like this:
XmlNode paketNode = doc.SelectSingleNode("/omds20:OMDS/omds20:PAKET", xmlnsManager);

Related

Xml path that have multiple namespaces

I can't figure out what namespaces need to be used for following Xml (sample):
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ResponseCharge xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ResponseInfo xmlns="http://www.example.net">
<ResponseDetail>
<ResponseCode>00</ResponseCode>
<RequestIdentifier>1029034</RequestIdentifier>
<RetrievalReferenceNumber>634716660366</RetrievalReferenceNumber>
<ProcessingTime>00:03:314</ProcessingTime>
</ResponseDetail>
<ResponseTransactionDetail>
<AVSResponseCode />
<CVVResponseCode />
<AuthorizationSourceCode />
<AuthorizationNumber>004454</AuthorizationNumber>
</ResponseTransactionDetail>
<EMVResponseData />
</ResponseInfo>
</ResponseCharge>
</s:Body>
</s:Envelope>
My code looks like this atm:
XmlDocument doc = new XmlDocument();
doc.Load(responseXmlFile);
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
//nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
//nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
//nsmgr.AddNamespace("", "http://www.example.net");
// getting NULL here
XmlNode node = doc.SelectSingleNode("/s:Envelope/s:Body/ResponseCharge/ResponseInfo/ResponseTransactionDetail/AuthorizationNumber", nsmgr);
I'm following this post: Namespace Manager or XsltContext needed
You need to include the namespace in your query for the elements in the http://www.example.net/ namespace.
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
nsmgr.AddNamespace("ex", "http://www.example.net");
XmlNode node = doc.SelectSingleNode(
"/s:Envelope/s:Body/ResponseCharge/ex:ResponseInfo/ex:ResponseTransactionDetail/ex:AuthorizationNumber",
nsmgr);
I've arbitrarily picked ex as the prefix here. What's defined in the XmlNamespaceManager only relates to your XPath query, the prefixes used in the document aren't relevant.
Alternatively, I'd suggest you use LINQ to XML:
XNamespace ns = "http://www.example.net"
var doc = XDocument.Load(responseXmlFile);
var authNo = (int)doc.Descendants(ns + "AuthorizationNumber").Single();

Replace xml document parameters using c#

I want to replace following #eleval2,#eleval4 parameters with some other values using c#.net.Please help me to do it.
<root>
<element1>
<element2>
#eleval2
</element2>
</element1>
<element3>
<element4>
<element4>
#eleval4
</element4>
</element4>
</element3>
Directly updating node:
XmlDocument xml = new XmlDocument();
xml.Load("file_name.xml");
xml.SelectSingleNode("/root/element1/element2").InnerText = "NewValue";
For looping:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("path_here");
XmlNodeList tagNodes= xmlDoc.GetElementsByTagName("tag_of_your_interest");
//Loop through first child of above list
foreach (XmlNode chapter in tagNodes[0].ChildNodes)
{
//Perform your updates here
}
Load from string:
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
Get all list of nodes matches path:
XmlNodeList xnList = doc.SelectNodes("/sections/notebooks/article");

Trying to change a XML node with no success

I'm trying to change a the value for the model atribute from the following .xml file.
<MTConnectDevices xmlns="urn:mtconnect.org:MTConnectDevices:1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:mtconnect.org:MTConnectDevices:1.1 http://www.mtconnect.org/schemas/MTConnectDevices_1.1.xsd">
<Header version="1.1" sender="Company MTConnect Instance" creationTime="2010-08-26T19:00:47-07:00" instanceId="2" bufferSize="131072" />
<Devices>
<Device name="XX" iso841Class="1" uuid="000" id="id1001">
<Description manufacturer="name" serialNumber="Serial Number" model="UNDEFINED">
</Description>
This is what I've tried but it's not working as it's not changing the value for model.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(mypath);
var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ns", xmlDoc.DocumentElement.NamespaceURI);
var node = xmlDoc.SelectSingleNode("/ns:MTConnectDevices/ns:Header/ns:Devices/ns:Device/ns:Description", nsmgr);
node.Attributes["model"].Value = "changed";
xmlDoc.Save(mypath);
Can anyone give me a hand and tell me how to fix this?
Your xml contains namespaces, so you have to use them while retrieving node.
It can be done something like this:
var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ns", xmlDoc.DocumentElement.NamespaceURI);
var node = xmlDoc.SelectSingleNode("/ns:MTConnectDevices/ns:Devices/ns:Device/ns:Description", nsmgr);

How do I find a XML element using c# when I know the exact path?

How do I get information from an xml document?
I have an xml document at c:\temp\data.xml and am using visual studio.
The closest I can figure is:
XmlDocument xdoc = new XmlDocument();
xdoc.Load(#"C:\temp\data.xml");
date = xdoc.SelectSingleNode("/forcast_informat…
The XML document looks like this:
<?xml version="1.0"?>
-<xml_api_reply version="1">
-<weather section="0" row="0" mobile_zipped="1" mobile_row="0" tab_id="0" module_id="0">
-<forecast_information>
etc etc...
<current_date_time data="2012-08-09 21:53:00 +0000"/>
etc, etc...
All I want to do is grab that date of 2012-08-09 21:53:00 +0000...any suggestions?
This should do the trick:
XmlDocument xdoc = new XmlDocument();
xdoc.Load(#"C:\temp\data.xml");
XmlNode dataAttribute = xdoc.SelectSingleNode("/xml_api_reply/weather/forecast_information/current_date_time/#data");
Console.WriteLine(dataAttribute.Value);
Try this. This will load current date and time for every forecast:
XmlDocument XMLDoc = new XmlDocument();
XMLDoc.Load(XMLDocumentPath);
XmlNodeList NodeList = XMLDoc.SelectNodes("/xml_api_reply/weather/forecast_information/");
foreach(XmlNode Node in NodeList)
{
string DTime = Node["current_date_time"].InnerText;
//Do something with DTime
}

XML - how to use namespace prefixes

I have this XML at http://localhost/file.xml:
<?xml version="1.0" encoding="utf-8"?>
<val:Root xmlns:val="http://www.hw-group.com/XMLSchema/ste/values.xsd">
<Agent>
<Version>2.0.3</Version>
<XmlVer>1.01</XmlVer>
<DeviceName>HWg-STE</DeviceName>
<Model>33</Model>
<vendor_id>0</vendor_id>
<MAC>00:0A:DA:01:DA:DA</MAC>
<IP>192.168.1.1</IP>
<MASK>255.255.255.0</MASK>
<sys_name>HWg-STE</sys_name>
<sys_location/>
<sys_contact>
HWg-STE:For more information try http://www.hw-group.com
</sys_contact>
</Agent>
<SenSet>
<Entry>
<ID>215</ID>
<Name>Home</Name>
<Units>C</Units>
<Value>27.7</Value>
<Min>10.0</Min>
<Max>40.0</Max>
<Hyst>0.0</Hyst>
<EmailSMS>1</EmailSMS>
<State>1</State>
</Entry>
</SenSet>
</val:Root>
I am trying to read this from my c# code:
static void Main(string[] args)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load("http://localhost/file.xml");
XmlElement root = xmlDoc.DocumentElement;
// Create an XmlNamespaceManager to resolve the default namespace.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("val", "http://www.hw-group.com/XMLSchema/ste/values.xsd");
XmlNodeList nodes = root.SelectNodes("/val:SenSet/val:Entry");
foreach (XmlNode node in nodes)
{
string name = node["Name"].InnerText;
string value = node["Value"].InnerText;
Console.Write("name\t{0}\value\t{1}", name, value);
}
Console.ReadKey();
}
}
Problem is that the node is empty. I understand this is a common newbie problem when reading XML, still not able to solve what I am doing wrong, probably something with the Namespace "val" ?
You need to pass the namespace manager into the SelectNodes()
method.
Edit: corrected code
XmlNodeList nodes = root.SelectNodes("/val:Root/SenSet/Entry", nsmgr);
Just change you Xpath to:
XmlNodeList nodes1 = root.SelectNodes("/val:Root/SenSet/Entry",nsmgr);
Or:
XmlNodeList nodes = root.SelectNodes("SenSet/Entry");
Your xpath query string should be:
XmlNodeList nodes = root.SelectNodes("/val:Root/SenSet/Entry", nsmgr);
or more concisely,
XmlNodeList nodes = root.SelectNodes("//SenSet/Entry", nsmgr);

Categories

Resources