How to read a node in an xml in this format - c#

I have an getting an xml response on this format
<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n
<PlatformResponse xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://platform.intuit.com/api/v1\">\r\n
<ErrorMessage>OAuth Token rejected</ErrorMessage>\r\n
<ErrorCode>270</ErrorCode>\r\n
<ServerTime>2012-06-19T00:01:31.5150146Z</ServerTime>\r\n
</PlatformResponse>
I need to grab the value in the <ErrorCode> node, for that I did the following but it is not getting any values..
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlResponse);
XmlNodeList xnList = xml.SelectNodes("PlatformResponse");
foreach (XmlNode xn in xnList)
{
result.Message = xn["ErrorCode"].InnerText;
}
Any help would be much appreciated.

There seems to be some dirt in your PlatformResponse node that's giving problems, ( xmlns:xsd= etc... )
Using this xml
String sXml = #"<?xml version='1.0' encoding='utf-8'?>
<PlatformResponse >
<ErrorMessage>OAuth Token rejected</ErrorMessage>
<ErrorCode>270</ErrorCode>
<ServerTime>2012-06-19T00:01:31.5150146Z</ServerTime>
</PlatformResponse>";
And select like
XmlNodeList xnList = xml.SelectNodes("/PlatformResponse");
Your code works fine.

I just tested the code and it does work fine:
XmlDocument xml = new XmlDocument();
XmlTextReader reader = new XmlTextReader("Path_to_your_xml");
xml.Load(reader);
XmlNodeList xnList = xml.SelectNodes("PlatformResponse");
foreach (XmlNode xn in xnList)
{
MessageBox.Show(xn["ErrorCode"].InnerText);
}

For this, since the attribute is on the main document element itself, you can simply do
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlText);
result.Message = xml.DocumentElement["ErrorCode"].InnerText

Related

how to get(read) data from xmldocument in windows phone, c#

I'm getting data from a web service in my phone application and get the response to xmldocument like below.
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.LoadXml(newx2);
Ther result of XmlDoc is like below.now I want to get the values from this.
<root>
<itinerary>
<FareIndex>0</FareIndex>
<AdultBaseFare>4719</AdultBaseFare>
<AdultTax>566.1</AdultTax>
<ChildBaseFare>0</ChildBaseFare>
<ChildTax>0</ChildTax>
<InfantBaseFare>0</InfantBaseFare>
<InfantTax>0</InfantTax>
<Adult>1</Adult>
<Child>0</Child>
<Infant>0</Infant>
<TotalFare>5285.1</TotalFare>
<Airline>AI</Airline>
<AirlineName>Air India</AirlineName>
<FliCount>4</FliCount>
<Seats>9</Seats>
<MajorCabin>Y</MajorCabin>
<InfoVia>P</InfoVia>
<sectors xmlns:json="http://james.newtonking.com/projects/json">
</itinerary>
</root>
I tried with this.
XmlNodeList xnList = XmlDoc.SelectNodes("/root[#*]");
but it gives null result. the count is 0. how can I read the data from this.hope your help with this.thanx.
You can use System.Xml.Linq.XElement to parse an xml:
XElement xRoot = XElement.Parse(xmlText);
XElement xItinerary = xRoot.Elements().First();
// or xItinerary = xRoot.Element("itinerary");
foreach (XElement node in xItinerary.Elements())
{
// Read node here: node.Name, node.Value and node.Attributes()
}
If you want to use XmlDocument you can do like this:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlText);
XmlNode itinerary = xmlDoc.FirstChild;
foreach (XmlNode node in itinerary.ChildNodes)
{
string name = node.Name;
string value = node.Value;
// you can also read node.Attributes
}
You can get the value of a particular element like,
var fareIndex = XmlDoc.SelectSingleNode("/root/itinerary/FareIndex").InnerText;
If you want to get the list of all elements that come under root/itinerary -
XmlNodeList xnList = XmlDoc.SelectNodes("/root/itinerary/*");
This link might help you.

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

Unable to Read XML using C# and XmlDocument

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);

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);

Read a XML (from a string) and get some fields - Problems reading XML

I have this XML (stored in a C# string called myXML)
<?xml version="1.0" encoding="utf-16"?>
<myDataz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<listS>
<sog>
<field1>123</field1>
<field2>a</field2>
<field3>b</field3>
</sog>
<sog>
<field1>456</field1>
<field2>c</field2>
<field3>d</field3>
</sog>
</listS>
</myDataz>
and I'd like to browse all <sog> elements. For each of them, I'd like to print the child <field1>.
So this is my code :
XmlDocument xmlDoc = new XmlDocument();
string myXML = "<?xml version=\"1.0\" encoding=\"utf-16\"?><myDataz xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><listS><sog><field1>123</field1><field2>a</field2><field3>b</field3></sog><sog><field1>456</field1><field2>c</field2><field3>d</field3></sog></listS></myDataz>"
xmlDoc.Load(myXML);
XmlNodeList parentNode = xmlDoc.GetElementsByTagName("listS");
foreach (XmlNode childrenNode in parentNode)
{
HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value);
}
but seems I can't read a string as XML? I get System.ArgumentException
You should use LoadXml method, not Load:
xmlDoc.LoadXml(myXML);
Load method is trying to load xml from a file and LoadXml from a string. You could also use XPath:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
string xpath = "myDataz/listS/sog";
var nodes = xmlDoc.SelectNodes(xpath);
foreach (XmlNode childrenNode in nodes)
{
HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value);
}
Use Linq-XML,
XDocument doc = XDocument.Load(file);
var result = from ele in doc.Descendants("sog")
select new
{
field1 = (string)ele.Element("field1")
};
foreach (var t in result)
{
HttpContext.Current.Response.Write(t.field1);
}
OR : Get the node list of <sog> tag.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(myXML);
XmlNodeList parentNode = xmlDoc.GetElementsByTagName("sog");
foreach (XmlNode childrenNode in parentNode)
{
HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("field1").InnerText);
}
The other answers are several years old (and do not work for Windows Phone 8.1) so I figured I'd drop in another option. I used this to parse an RSS response for a Windows Phone app:
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(xml_string);
Or use the XmlSerializer class.
XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));
I used the System.Xml.Linq.XElement for the purpose. Just check code below for reading the value of first child node of the xml(not the root node).
string textXml = "<xmlroot><firstchild>value of first child</firstchild>........</xmlroot>";
XElement xmlroot = XElement.Parse(textXml);
string firstNodeContent = ((System.Xml.Linq.XElement)(xmlroot.FirstNode)).Value;

Categories

Resources