SelectNodes return null [duplicate] - c#

This question already has answers here:
SelectSingleNode returns null when tag contains xmlNamespace
(4 answers)
Closed 7 years ago.
I am using SelectNodes to read xml nodes but i am getting null when i try GetElementsByTagName i get the values.
XmlDocument xml = new XmlDocument();
xml.Load(DownloadFile);
XmlNodeList xmlnode;
xmlnode = xml.GetElementsByTagName("CruisePriceSummaryResponse");
for (int i = 0; i < xmlnode.Count; i++)
{
XmlNodeList rooms = xml .SelectNodes("RoomSize/CruisePriceSummaryRoomSize");
for(int j = 0; j < rooms.Count; j++)
{
string bestFare = rooms[j].SelectSingleNode("BestFare/TotalPrice").InnerText;
string fullFare = rooms[j].SelectSingleNode("FullFare/TotalPrice").InnerText;
// do whatever you need
}
}
I want to read TotalPrice from BestFare and FullFare Each child has two innerchilds BestFare and FullFareand I need to read each TotalPrice.
This is my XML
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCruisePriceSummaryResponse
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/OpenseasAPI.ServiceModel">
<CruisePriceSummaryResponse>
<AvailablePromos
xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d3p1:string>FLA</d3p1:string>
<d3p1:string>FLB</d3p1:string>
</AvailablePromos>
<Brand>PA</Brand>
<CruiseCategory i:nil="true"/>
<RoomSize>
<CruisePriceSummaryRoomSize>
<BestFare>
<TotalPrice>2798.0000000</TotalPrice>
</BestFare>
<FullFare>
<TotalPrice>3198.000000</TotalPrice>
</FullFare>
<PaxCount>2</PaxCount>
</CruisePriceSummaryRoomSize>
<CruisePriceSummaryRoomSize>
<BestFare>
<TotalPrice>2796.000000</TotalPrice>
</BestFare>
<FullFare>
<TotalPrice>4196.000000</TotalPrice>
</FullFare>
<PaxCount>4</PaxCount>
</CruisePriceSummaryRoomSize>
</RoomSize>
<ShipCode>PD</ShipCode>
</CruisePriceSummaryResponse>
<CruisePriceSummaryResponse>
<AvailablePromos
xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d3p1:string>FLA</d3p1:string>
<d3p1:string>LF1</d3p1:string>
</AvailablePromos>
<Brand>PA</Brand>
<RoomSize>
<CruisePriceSummaryRoomSize>
<BestFare>
<TotalPrice>1298.000000</TotalPrice>
</BestFare>
<FullFare>
<TotalPrice>3498.000000</TotalPrice>
</FullFare>
<PaxCount>2</PaxCount>
</CruisePriceSummaryRoomSize>
<CruisePriceSummaryRoomSize>
<BestFare>
<TotalPrice>1796.000000</TotalPrice>
</BestFare>
<FullFare>
<TotalPrice>5396.000000</TotalPrice>
</FullFare>
<PaxCount>4</PaxCount>
</CruisePriceSummaryRoomSize>
</RoomSize>
<ShipCode>PJ</ShipCode>
</CruisePriceSummaryResponse>
</ArrayOfCruisePriceSummaryResponse>
Help would be appreciated. I do not want to use linq as this is a SSIS project using VS2008 and it doesnot support linq.
Thanks in advance

You never load or read the source XML. Your code
XmlDocument xml = new XmlDocument();
XmlNodeList xmlnode;
xmlnode = xml.GetElementsByTagName("CruisePriceSummaryResponse");
creates an empty XML document, and then tries to get elements from the empty xml.
You need to call XmlDocument.Load or XmlDocument.LoadXML to read the xml from a file or a string.
XmlDocument xml = new XmlDocument();
xml.Load("pathtosomefile.xml");
XmlNodeList xmlnode = xml.GetElementsByTagName("CruisePriceSummaryResponse");

Related

how to remove element id from xml using c# [duplicate]

This question already has answers here:
remove attribute if it exists from xmldocument
(2 answers)
Closed 4 years ago.
this is my XML
<root>
<CHILD ="1" UID="1">
<GrandChild>1</GrandChild>
</CHILD>
<CHILD ="2" UID="2">
<GrandChild>2</GrandChild>
</CHILD>
</root>
how can i remove child 1 from xml
Your xml is invalid because of the 'Child ="1"' syntax.
With valid xml you can parse using System.Xml.XmlDocument:
using System.Xml;
Create a new XmlDocument object:
XmlDocument xmlDoc = new XmlDocument(); // Create an XML document object
If you are reading xml from a file, use xmlDoc.Load(string filename):
xmlDoc.Load("yourXMLFile.xml");
If you are reading xml from a string, use xmlDoc.LoadXml(string xml):
xmlDoc.LoadXml(xmlStringVariable);
From there, you can parse through your XML by the tag names and child nodes. Here is a simple example, but hopefully it will give you a start:
XmlNodeList childList = xmlDoc.GetElementsByTagName("CHILD");
var _child = childList[0];
for (int i = 0; i < childList.Count; i++)
{
// Do work
// Loop through child nodes
for(int c = 0; c < childList[i].ChildNodes.Count; c++)
{
// Do something with child nodes
var _childNode = childList[i].ChildNodes[c].InnerXml;
}
}

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.

How read data from xml string in C# [duplicate]

This question already has answers here:
Deserializing XML from String
(2 answers)
Closed 6 years ago.
I get this XML string for my web page, how can I retrieve data from that XML and assign values to labels in my web page?
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<things>
<bat>201400000586</bat>
<status>Y</status>
<totalAmount>3090</totalAmount>
<billno>P2355</billno>
<ReceiveDate>27/04/2015 06:22:18 PM</ReceiveDate>
</things>
Firstly load the Xml Doc using XMLDocument
XDocument doc = XDocument.Load(filePath);
XElement rootElm = doc.Element("things")
Now using linq you can fetch IENumerable
IEnumerable<XElement> childList = from Y in rootElm.Root.Elements()
select Y;
Now ou can loop through list items
foreach (XElement elm in childList)
{
//Here you can access elements this way
Console.log(elm.Element("status").Value);
..........
}
Here you can even edit the contents in xml file and save them.
Assign the values for the XElement type elements in the loop
doc.Save(filePath);
There are different ways to do this. Here is one.
You'll need to add "using System.Xml.XPath;"
XPathDocument doc = new XPathDocument(Server.MapPath("~/XMLFile1.xml"));
XPathNavigator nav = doc.CreateNavigator();
XPathExpression exp = nav.Compile(#"/things");
foreach (XPathNavigator item in nav.Select(exp))
{
label1.Text = item.SelectSingleNode("bat").ToString();
label2.Text = item.SelectSingleNode("totalAmount").ToString();
}
Or you can load it as a string, then use EITHER XmlElement or XmlNode with such a simple XML structure.
XmlDocument m_xml = new XmlDocument();
m_xml.LoadXml(#"<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes"" ?><things><bat>201400000586</bat><status>Y</status><totalAmount>3090</totalAmount><billno>P2355</billno><ReceiveDate>27/04/2015 06:22:18 PM</ReceiveDate></things>");
XmlNode node_bat = m_xml.SelectSingleNode("//things/bat");
XmlNode node_totalAmount = m_xml.SelectSingleNode("//things/totalAmount");
XmlElement node_bat1 = m_xml.DocumentElement["bat"];
XmlElement node_totalAmount1 = m_xml.DocumentElement["totalAmount"];
label1.Text = node_bat1.InnerText;
label2.Text = node_totalAmount1.InnerText;

How to get the node value

I am trying to fetch the value for name attribute but unable to do it.
<Person>
<DOB localDate="2015-07-02" utcDate="2015-07-02" localTime="09:26:00" utcTime="08:26:00" />
<Info name="Bruce Wayne" Country="GB" Zone="3" />
</Person>
Try This:
string str= "";
XmlDocument xdoc = new XmlDocument();
xdoc.Load("Your XML Path");
XmlNodeList elements = xdoc.GetElementsByTagName("Info");
for (int i = 0; i < elements.Count; i++)
{
str= elements[i].Attributes["name"].Value;
}
MessageBox.Show(str);
Unless you have a specific reason for using an XmlDocument, use the newer XDocument instead, linq makes finding xml nodes very easy.
Try this
var name = xDoc.Root.Element("Info").Attribute("name").Value;

Read the XML with different elements in C#

I know, that there are a lot of question about parsing C#, but I couldn't find answer.
So, I need to write a DLL for parsing XML, but with some features, as I don't know what elements are in XML file. I need to parse all nodes of file and their elements. How can I do it? Now, I'm working with simple file
<reg>
<email_login>paykforcycvert#reincarnate.com</email_login>
<email_password>nDOUn3TybD</email_password>
</reg>
and my dll code now is
public XmlNodeList GetElementsName(string path)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("email_login");
return nodeList;
}
It should return "paykforcycvert#reincarnate.com".
My console app:
XMLWorker worker = new XMLWorker();
string path = "file:///D:/temp/test.xml";
XmlNodeList nodeList = worker.GetElementsName(path);
for (int i = 0; i < nodeList.Count; i++)
Console.WriteLine(nodeList[i].InnerText);
Console.ReadLine();
But it returns "paykforcycvert#reincarnate.comnDOUn3TybD"
How can I parse differently?
Use LINQ to XML:
XElement reg = XElement.Load(path);
string login = (string)reg.Element("email_login");
BTW your code works fine for me. Make sure you are not selecting all elements instead of email_login only. I.e. if you are getting child nodes XmlNodeList nodeList = xmlDoc.ChildNodes; instead of getting elements by tag name, then you will have your results.
Or possibly you have several elements named as email_login. E.g. following xml will produce your results with your code:
<reg>
<email_login>paykforcycvert#reincarnate.com</email_login>
<email_login>nDOUn3TybD</email_login>
</reg>
i ran the exact same code you gave and got paykforcycvert#reincarnate.com as output so my guess is that you haven't build your project after you fixed something or it wasn't cleaned.
try to clean the project and run it again
You can do it this way
public List<String> getElementValues(string path,string elementName)
{
XElement doc= XElement.Load(path);
var elementList=doc.Descendants().Elements();
return elementList.Where(x=>x.Name.LocalName==elementName)
.Select(y=>y.Value)
.ToList();
}
You can now get all the values of element with name email_login
var values=getElementValues(path,"email_login");
I ran following code after coping the XML data you provided in XMLFile.xml to emulate output:
class Program
{
static void Main(string[] args)
{
XMLWorker worker = new XMLWorker();
//
string path = #"C:\Users\abc\Desktop\ConsoleApplication1\ConsoleApplication1\XMLFile.xml";
XmlNodeList nodeList = worker.GetElementsName(path);
for (int i = 0; i < nodeList.Count; i++)
Console.WriteLine(nodeList[i].InnerText);
Console.ReadLine();
}
}
public class XMLWorker
{
public XmlNodeList GetElementsName(string path)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("email_login");
return nodeList;
}
}
But for me it is working fine.
You can also use XPath query:
XmlNodesList nodesList = xmlDoc.SelectNodes("//email_login"));
foreach(string oneNode in nodesList)
{
Console.Write(oneNode.InnerText);
}

Categories

Resources