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;
Related
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.
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");
This question already has answers here:
Extract nodes from string containing xml
(2 answers)
Closed 8 years ago.
My xml is:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>http://localhost:2511/SF/sitemap_1.xml</loc>
<lastmod>2013-11-11T04:17:57+00:00</lastmod>
</sitemap>
<sitemap>
<loc>http://localhost:2511/SF/sitemap_2.xml</loc>
<lastmod>2013-11-11T04:17:57+00:00</lastmod>
</sitemap>
</urlset>
And I try to change each <lastmod> value like this :
XmlDocument doc = new XmlDocument();
doc.Load(HttpRuntime.AppDomainAppPath + "sitemap_index.xml"); //Doc is loaded successfully
//XmlNodeList nodeList = doc.SelectNodes("/urlset/sitemap/lastmod");//I also try this one
XmlNodeList nodeList = doc.DocumentElement.SelectNodes("/urlset/sitemap/lastmod");
foreach (XmlNode xmlNode in nodeList)
{
xmlNode.InnerText = DateTime.Now.ToString();
}
But I always get nodeList count 0. What is my mistake.Thanks for help.
Replace this line
XmlNodeList nodeList = doc.DocumentElement.SelectNodes("/urlset/sitemap/lastmod");
with
XmlNodeList nodeList = doc.GetElementsByTagName("lastmod");
I don't how to extract the values from XML document, and am looking for some help as I'm new to C#
I am using XmlDocument and then XmlNodeList for fetching the particular XML document
Here is my code
XmlNodeList XMLList = doc.SelectNodes("/response/result/doc");
And my XML looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<result>
<doc>
<long name="LoadID">494</long>
<long name="EventID">5557</long>
<str name="XMLData"><TransactionDate>2014-05-28T14:17:31.2186777-06:00</TransactionDate><SubType>tblQM2222Components</SubType><IntegerValue title="ComponentID">11111</IntegerValue></str></doc>
<doc>
<long name="LoadID">774</long>
<long name="EventID">5558</long>
<str name="XMLData"><TransactionDate>2014-05-28T14:17:31.2186777-06:00</TransactionDate><SubType>tblQM2222Components</SubType><IntegerValue title="ComponentID">11111</IntegerValue></str></doc>
</result>
</response>
In this i have to fetch every the XMLData data that is under every doc tag and i have to fetch last doc tag EventID.
var xml = XDocument.Parse(xmlString);
var docs = xml.Root.Elements("doc");
var lastDocEventID = docs.Last()
.Elements("long")
.First(l => (string)l.Attribute("name") == "EventID")
.Value;
Console.WriteLine ("Last doc EventId: " +lastDocEventID);
foreach (var doc in docs)
{
Console.WriteLine (doc.Element("str").Element("TransactionDate").Value);
}
prints:
Last doc EventId: 5558
2014-05-28T14:17:31.2186777-06:00
2014-05-28T14:17:31.2186777-06:00
You can use two XPath expressions to select the nodes you want. To answer each part of your question in turn:
To select all of the XMLData nodes:
XmlNodeList XMLList
= doc.SelectNodes("/response/result/doc/str[#name='XMLData']");
To select the last EventId:
XmlNode lastEventIdNode =
doc.SelectSingleNode("/response/result/doc[position() =
last()]/long[#name='EventID']");
If not all doc nodes are guaranteed to have an event id child node, then you can simply:
XmlNodeList eventIdNodes =
doc.SelectNodes("/response/result/doc[long[#name='EventID']]");
XmlNode lastNode = eventIdNodes[eventIdNodes.Count - 1];
That should give you what you've asked for.
Update;
If you want the XML data inside each strXml element, you can use the InnerXml property:
XmlNodeList xmlList
= doc.SelectNodes("/response/result/doc/str[#name='XMLData']");
foreach(XmlNode xmlStrNode in xmlList)
{
string xmlInner = xmlStrNode.InnerXml;
}
There's one result tag short in your xml.
Try using this. It's cleaner too imho
XmlNodeList docs = doc.SelectSingleNode("response").SelectSingleNode("result").SelectNodes("doc");
Then you can use a combination of SelectSingleNode, InnerText, Value to get the data from each XmlNode in your list.
For example if you want the EventID from the first doc tag:
int eventID = int.Parse(docs[0].SelectSingleNode("long[#name='EventID']").InnerText);
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;