How do I get a specific value from xml in c# - c#

My problem is a bit typical and I am very new to working with xml. Please view the following code:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(myxml);
Response.Write("<p><strong>First Result</strong><br/>");
for (int nodeCount = 0; nodeCount < xDoc.ChildNodes.Count; nodeCount++)
{
Response.Write(xDoc.ChildNodes[nodeCount].Name + ":");
Response.Write(xDoc.ChildNodes[nodeCount].InnerXml + "<br/>");
}
Response.Write("</p>");
.. and the output I get in the aspx page is as follows:
First Result
xml:
Response:OK122.160.37.198ININDIAWEST BENGALKOLKATA70015522.569788.3697+05:30
I want the values 'WEST BENGAL' and 'KOLKATA' from it. I am not being able to read/write this in xml format so that I can grab the required nodes and their values. How to do that?

You can use XPath to search the XML. use your "xDoc" variable
XPathDocument doc = new XPathDocument(XmlReader(xDoc));
XPathNavigator nav = doc.CreateNavigator();
XPathExpression exprName = nav.Compile(xPathName);
XPathNodeIterator iteratorName = nav.Select(exprName)

You could use the Descendants() function on the XDocument itself, consider this example:
(Note - have made assumptions about how your data looks)
using System.Xml.Linq;
static void Main()
{
var xml = "<Data><ININDIA>WEST BENGAL</ININDIA><ININDIA>KOLKATA</ININDIA></Data>";
var xd = XDocument.Parse(xml);
//get all `XElement` objects with the name "ININDIA"
foreach (var e in xd.Root.Descendants()
.Where(e=>e.Name.LocalName=="ININDIA"))
{
Console.WriteLine(e.Value);
}
}
will produce
WEST BENGAL
KOLKATA

Related

get grandson text using xml document in c#

I'm using XmlDocument in C# and I would like to know how to get grandson data of the root?
<tRoot>
<One>
<a>15</a>
<b>11</b>
<c>1</c>
<d>11.35</d>
<e>0</e>
<f>289</f>
</One>
<Two>
<a>0</a>
<b>11</b>
<c>1</c>
<d>0.28</d>
<e>0</e>
<f>464</f>
</Two>
</tRoot>
and I want the ability to get a of One and also a of Two
I tried:
var doc = new XmlDocument();
doc.Load(Consts.FileConst);
var docXml = doc["One"];
if (docXml != null)
{
float valFromXml = float.Parse(docXml["a"].InnerText);
}
The issue is that docXml is null
Any assitance?
As suggested above, XDocument would be a better alternative. If, however, you still want to use XmlDocument, you can iterate through the children using
var doc = new XmlDocument();
doc.Load(Consts.FileConst);
foreach(XmlNode xmlNode in doc.DocumentElement.ChildNodes) {
//access a/b/c/d/e using:
xmlNode.ChildNodes[0].InnerText; //for a
xmlNode.ChildNodes[1].InnerText; //for b
}
Try this:
XmlDocument d = new XmlDocument();
d.LoadXml("<tRoot><One><a>15</a><b>11</b><c>1</c><d>11.35</d><e>0</e><f>289</f></One><Two><a>0</a><b>11</b><c>1</c><d>0.28</d><e>0</e><f>464</f></Two></tRoot>");
XmlNodeList itemNodes = d.SelectNodes("//*/a");

XML - Write a single node

I got this function for simply get the inner text of my xml:
XmlDocument document = new XmlDocument();
document.Load("game.xml");
string content = document.SelectSingleNode("Game/Client-Version").InnerText;
(this is the xml file (due to complications with stackoverflow posted on pastebin)): http://pastebin.com/EEeFAJpC
And now I am exactly looking for the function above, just to write. Like
document.WriteSingleNode("Game/Client-Version", "texttowrite");
I did not find anything helping me out.
This should work
XmlElement x = document.SelectSingleNode("Game/Client-Version") as XmlElement;
x.InnerText = "texttowrite";
Create your own extension method:
public void WriteSingleNode(this XmlDocument document, string NodeName, string InnerText)
{
// Create a new element node.
XmlNode newElem = document.CreateNode("element", "pages", "");
newElem.InnerText = InnerText;
Console.WriteLine("Add the new element to the document...");
document.DocumentElement.AppendChild(newElem);
Console.WriteLine("Display the modified XML document...");
Console.WriteLine(document.OuterXml);
}

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

Getting sibling using xPath

I am currently working on a .net C# solution that returns 2 sibling nodes. Using Xpath 1.0
A small example of my xml doc is this:
<PLAY>
<SCENE>
<SPEAKER>
</SPEAKER>
<LINE>
</LINE>
</SCENE>
</PLAY>
I am using the following code to get the line and the speaker but i dont know why i get the entire xml doc being passed in instead of just the sibling (speaker)
I have :
List speakers = new List();
XmlDocument myDoc = new XmlDocument();
myDoc.Load(textXMLFile.Text.ToString());
// Clear the text box...
textResults.Text = "";
// ADD THIS...
XPathNavigator theNav = myDoc.CreateNavigator();
XPathNavigator theNav2 = myDoc.CreateNavigator();
//XmlNodeList theNodes =
// myDoc.SelectNodes(textXPath.Text.ToString());
textXPath.Text = "//SPEECH/LINE";
string val = "//SPEECH/SPEAKER";
XPathNodeIterator theNodes = theNav.Select(textXPath.Text.ToString());
XPathNodeIterator theNodes2 = theNav2.Select(val);
StringBuilder output = new StringBuilder();
while (theNodes.MoveNext())
{
if (theNodes.Current.InnerXml.ToString() == "Upon my sword.")
{
break;
}
else
{
speakers.Add(theNodes2.Current.InnerXml.ToString());
speakers.Add(theNodes2.Current.InnerXml.ToString());
}
}
for (int i =0; i < speakers.Count; ++i)
{
output.Append (speakers[i]+" ");
}
MessageBox.Show(""+output);
theNodes.Current.InnerXml.ToString() works fine for returning the line but theNodes2.Current.InnerXml.ToString() seems to return the entire XML instead of the speaker.
Any comments or suggestions are appreciated.
After staring at this for awhile i totally missed that i needed to move theNodes2 also in the while loop like so
while(theNodes2.MoveNext())
Thanks All
//SPEECH/LINE is not going to find anything in a document where the elements are named "play", "scene", "speaker", and "line". Please try to be more careful in formulating your questions. Downvoting.

Help in parsing XML, simple string - but I can't seem to parse it

I have the following XML:
<iq xmlns="jabber:client" to="39850777771287777738178727#guest.google.com/agsXMPP" xml:lang="en" id="sub23" from="search.google.com" type="result">
<pubsub xmlns="http://jabber.org/protocol/pubsub">
<subscription subscription="subscribed" subid="5077774B57777BD77770" node="search" jid="39850777771287777738178727#guest.google.com/agsXMPP" />
</pubsub>
</iq>
I've tried parsing with linq to sql, but it doesn't seem to understand that these are different nodes. It groups the whole iq into a single element.
Can anyone help in parsing this using XML?
The data I want to get is the subid="5077774B57777BD77770" and the id="sub23"
Thanks!
Edit:
Here's the code I have, tried doing it in two ways:
XDocument doc = XDocument.Parse("<xml>" + iq.ToString() + "</xml>");
var results = from feed in doc.Elements("xml")
select new
{
Id = (string)feed.Element("iq").Attribute("id"),
Subid = (string)feed.Element("iq").Element("pubsub").Element("subscription").Attribute("subid")
};
and
var doc = new System.Xml.XmlDocument();
doc.LoadXml(iq.ToString());
var searchId = doc.Attributes["id"];
var subid = doc.SelectSingleNode("/pubsub/subscription").Attributes["subid"];
As Dimitre pointed out, you have a namespace issue. This will work:
using System;
using System.Xml;
namespace XMLTest
{
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable);
namespaces.AddNamespace("ns1", "jabber:client");
namespaces.AddNamespace("ns2", "http://jabber.org/protocol/pubsub");
doc.Load("xmltest.xml");
XmlNode iqNode = doc.SelectSingleNode("/ns1:iq", namespaces);
string ID = iqNode.Attributes["id"].Value;
Console.WriteLine(ID);
XmlNode subscriptionNode = doc.SelectSingleNode("/ns1:iq/ns2:pubsub/ns2:subscription", namespaces);
string subID = subscriptionNode.Attributes["subid"].Value;
Console.WriteLine(subID);
Console.ReadLine();
}
}
}
Read this for an explanation and a complete code example how to evaluate an XPath expression that contains location steps with nodes whose names are in a default namespace and are unprefixed in the XML document..
I'm not sure if this is what you're after, but it works:
XNamespace jabber = "jabber:client";
XNamespace pubsub = "http://jabber.org/protocol/pubsub";
string xmltext = "<iq xmlns=\"jabber:client\" to=\"39850777771287777738178727#guest.google.com/agsXMPP\" xml:lang=\"en\" id=\"sub23\" from=\"search.google.com\" type=\"result\">\n"
+ "<pubsub xmlns=\"http://jabber.org/protocol/pubsub\">\n"
+ "<subscription subscription=\"subscribed\" subid=\"5077774B57777BD77770\" node=\"search\" jid=\"39850777771287777738178727#guest.google.com/agsXMPP\" />\n"
+ "</pubsub>\n"
+ "</iq>";
XDocument xdoc = XDocument.Parse(xmltext);
var iqelem = xdoc.Element(jabber + "iq");
var id = iqelem.Attribute("id").Value;
var subselem = iqelem.Element(pubsub + "pubsub").Element(pubsub + "subscription");
var subid = subselem.Attribute("subid").Value;
Console.WriteLine("SubId = {0}\nId={1}", subid, id);
I concur with Dimitre - the "empty" xmlns namespace at the top is probably causing the problem. I sometimes strip these out with a regex if they're not used, otherwise play around with XmlNameSpaceManager as described

Categories

Resources