How can I get some numbers from xml to int? [duplicate] - c#

This question already has answers here:
How does one parse XML files? [closed]
(12 answers)
Closed 8 years ago.
I have this xml file:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!--This file represents the results of running a test suite-->
<test-results name="<path>" total="1" errors="0" failures="0" not-run="0" inconclusive="0" ignored="0" skipped="0" invalid="0" date="2014-08-12" time="16:05:41">
<environment nunit-version="2.6.3.13283" (...)
(...)
</test-results>
I want to get value of total, errors to integers in program "total", "errors" and so on. How can I get this values?

thry this
XDocument xDoc = XDocument.Load(#"your path");
int total=0;
foreach (var elem in xDoc.Document.Descendants("test-results"))
{
total += int.Parse(elem.Attribute("total").Value);
}

Try below code :-
var xDoc = XDocument.Load("XMLFile1.xml");
foreach (var elem in xDoc.Document.Descendants("test-results"))
{
var total = int.Parse(elem.Attribute("total").Value);
var error = int.Parse(elem.Attribute("errors").Value);
}

Use following:
//path is the path to your xml file
XmlTextReader reader = new XmlTextReader(path);
XmlDocument doc = new XmlDocument();
XmlNode node = doc.ReadNode(reader);
foreach (XmlNode chldNode in node.ChildNodes)
{
//Read the attribute Name
if (chldNode.Name.ToString().Equals("test-results"))
{
int total = Int32.Parse(chldNode.Attributes["total"].Value.ToString());
}
}

Related

How to Read value of any node element from XML formatted string? [duplicate]

This question already has answers here:
Can't use Descendants() or Elements() with xmlns
(3 answers)
Closed 6 years ago.
I have following XML formatted string in string __MessageIn variable:
string _MessageIn=
<?Label TSRAY|RESERVATION|317859|SUCCESS?>
<Reservation xmlns="reservation.fidelio.2.0" mfShareAction="NA" mfReservationAction="EDIT">
<HotelReference>
<hotelCode>TSRAY</hotelCode>
</HotelReference>
<confirmationID>Y6Z7TFJDK</confirmationID>
<reservationID>347557</reservationID>
<reservationOriginatorCode>JA</reservationOriginatorCode>
<originalBookingDate>2010-08-16T22:53:23.000</originalBookingDate>
<StayDateRange timeUnitType="DAY">
<startTime>2010-08-19T00:00:00.000</startTime>
<numberOfTimeUnits>3</numberOfTimeUnits>
</StayDateRange>
<GuestCounts>
<GuestCount>
<ageQualifyingCode>ADULT</ageQualifyingCode>
<mfCount>2</mfCount>
</GuestCount>
<GuestCount>
<ageQualifyingCode>CHILD</ageQualifyingCode>
<mfCount>0</mfCount>
</GuestCount>
</GuestCounts>
...................
..................
</Reservation>
I'm trying to get the value of hotelcode i.e. TSRAY from <hotelCode>TSRAY</hotelCode> but the code always returns NULL In HotelReference.
I tried below lines of code:
// query the XML document
XDocument doc = XDocument.Parse(_MessageIn);
var HotelReference = doc.Descendants("HotelReference").Select(x => new { HotelCode = x.Element("hotelCode").Value}).FirstOrDefault();
How can I get the required value from above XML formatted string variable?
Thanks in Advance!
This is happening because of namespaces being part of the xml.
There are 2 ways to overcome this issue, either remove the namespace "reservation.fidelio.2.0" then your code will work without issues. But this might not be feasable.
So we'll have to pass the namespace along with the nodenames when performing searches.. try the following and this would solve your issue. Hope this helps.
string ns = "reservation.fidelio.2.0";
string node = "HotelReference";
string elem = "hotelCode";
XName xn = XName.Get(node, ns);
XName xe = XName.Get(elem, ns);
var HotelReference = doc.Root.Descendants(xn).Select(x => new { HotelCode = x.Element(xe).Value }).FirstOrDefault();
Try this,
string _MessageIn="<?Label TSRAY|RESERVATION|317859|SUCCESS?> <Reservation xmlns='reservation.fidelio.2.0' mfShareAction='NA' mfReservationAction='EDIT'> <HotelReference> <hotelCode>TSRAY</hotelCode> </HotelReference> <confirmationID>Y6Z7TFJDK</confirmationID> <reservationID>347557</reservationID> <reservationOriginatorCode>JA</reservationOriginatorCode> <originalBookingDate>2010-08-16T22:53:23.000</originalBookingDate> <StayDateRange timeUnitType='DAY'> <startTime>2010-08-19T00:00:00.000</startTime> <numberOfTimeUnits>3</numberOfTimeUnits> </StayDateRange> <GuestCounts> <GuestCount> <ageQualifyingCode>ADULT</ageQualifyingCode> <mfCount>2</mfCount> </GuestCount> <GuestCount> <ageQualifyingCode>CHILD</ageQualifyingCode> <mfCount>0</mfCount> </GuestCount> </GuestCounts> ................... .................. </Reservation>";
string HotelCode = ""; // you can create HotelCode-Array to store all Hotelcodes
XmlDocument doc = new XmlDocument();
doc.LoadXml(_MessageIn);
XmlNodeList list=doc.GetElementsByTagName("hotelCode");
foreach (XmlNode node in list)
{
if (node.Name == "hotelCode")
{
HotelCode=node.InnerText;
}
}

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;

Change each value of same xml node with current date time [duplicate]

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

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;

How to parse an XML File [duplicate]

This question already has answers here:
How does one parse XML files? [closed]
(12 answers)
Closed 7 years ago.
I have an XML file that looks like:
<results>
<result>
<title>Welcome+to+The+JASON+Project%21</title>
<url>http%3A%2F%2Fwww.jason.org%2F</url>
<domain />
<inside_links>
<inside_link>
<description>News</description>
<url>http%3A%2F%2Fwww.jason.org%2FPublic%2FNews%2FNews.aspx</url>
</inside_link>
<inside_link>
<description>register</description>
<url>http%3A%2F%2Fwww.jason.org%2Fpublic%2Fregistration%2Fregistration.aspx</url>
</inside_link>
<inside_link>
<description>Argonauts</description>
<url>http%3A%2F%2Fwww.jason.org%2FPublic%2FArgonauts%2FArgonauts.aspx</url>
</inside_link>
<inside_link>
<description>Curriculum</description>
<url>http%3A%2F%2Fwww.jason.org%2FPublic%2FCurriculum%2FCurriculum.aspx</url>
</inside_link>
<inside_link>
<description>Credits</description>
<url>http%3A%2F%2Fwww.jason.org%2Fpublic%2FMisc%2FCredits.aspx</url>
</inside_link>
</inside_links>
<inside_keywords>National+Science+Education+Standards, National+Geographic+Society, Physical+Science, Professional+Development, Earth+Science</inside_keywords>
</result>
</results>
...And I'm very confused as to how to read it. I simply want to get the Title, Description, and URL into separate strings. Something like:
foreach line in lines
string title = gettitle;
string description = getdescription;
string url = geturl;
...I've read so many tutorials but all of them seem to not be relative to what i need to do.. Can somebody please help me out with this?
If you are using .NET 3.5, I'd suggest using LINQ to XML...
XDocument doc = XDocument.Load(filename);
XElement insideLinks = doc.Root.Element("result").Element("inside_links");
foreach (XElement insideLink in insideLinks.Elements())
{
string description = (string)insideLink.Element("description");
string url = (string)insideLink.Element("url");
}
This also lets you use the built-in "query" syntax so you could do something like this...
XDocument doc = XDocument.Load(filename);
XElement insideLinks = doc.Root.Element("result").Element("inside_links");
var allTitles = from XElement insideLink
in insideLinks.Elements("inside_link")
select (string)insideLink.Element("title");
(edited per comment)
To extend the LINQ to XML suggestion, you can use a select clause to create objects to represent the parsed links:
XDocument doc = XDocument.Load(filename);
var links = from link in doc.Descendants("inside_link")
select new
{
Description = (string)link.Element("description"),
Url = HttpUtility.UrlDecode((string)link.Element("url"))
};
foreach(var l in links)
Console.WriteLine("{1}", l.Url, l.Description);
In this case, links will be a sequence of objects that have an anonymous type with Description and Url properties, with Url decoded. This foreach would show something like this:
News
register
...
try this:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("yourfile.xml");
foreach (XmlNode result in xmlDoc.SelectNodes("/results/result"))
{
string title = result.SelectSingleNode("title").InnerText;
string url = result.SelectSingleNode("url").InnerText;
foreach (XmlNode insideLink in result.SelectNodes("inside_links/inside_link"))
{
string description = insideLink.SelectSingleNode("description").InnerText;
}
}

Categories

Resources