I have a XML document with my data in it, multiple entries for the same node fields (StudentID = FirstName, LastName, etc). How do I convert the nodes into string values for each StudentID section?
-
Can you give example of the current XML and the string you would like to have?o.k.w– o.k.w2009-10-30 23:51:38 +00:00Commented Oct 30, 2009 at 23:51
-
This is what I have so far: XmlDocument xmlReturnDoc = new XmlDocument(); xmlReturnDoc.Load("Data.xml"); XmlNodeList xnList = xmlReturnDoc.SelectNodes("/Students/Student"); foreach (XmlNode xn in xnList) { string firstName = xn["FirstName"].InnerText; string lastName = xn["LastName"].InnerText; MessageBox.Show("Name is: " + firstName + " " + lastName); } This works, but displays messageboxes one after the other with the First and Last Names of the entries. Is there a way to seperate the entries into strings?The Woo– The Woo2009-10-31 00:09:15 +00:00Commented Oct 31, 2009 at 0:09
3 Answers
You don't say much about what the xml looks like. But it could go something like this:
string xml = "<nodes><studentid><firstname>Name</firstname><lastname>last</lastname></studentid></nodes>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
foreach (XmlNode node in doc.SelectNodes("//studentid"))
{
string first = node["firstname"].InnerText;
string last = node["lastname"].InnerText;
}
If the data is in attributes use something along the lines of:
string first = node.Attributes["firstname"].Value;
You could also look into linq for xml if you have a schema.
Comments
Are you looking for the innerText of the node (the value inside the tags, but not the tag attribute data) or the outerXml (which has all the tag data)?
Also, are you using CDATAs? There's a little more you need to do to get data out of those properly.
Or, do you want it all at once -- in which case you'd use an XSLT transformation.
1 Comment
Copy and edited from http://www.csharp-examples.net/xml-nodes-by-name/
//on button click before the following:
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"
XmlNodeList xnList = xml.SelectNodes("/Names/Name");
StringBuilder sb = new StringBuilder();
string entry = "Name: {0} {1}\r\n";
foreach (XmlNode xn in xnList)
{
string firstName = xn["FirstName"].InnerText;
string lastName = xn["LastName"].InnerText;
sb.AppendFormat(entry, firstName, lastName);
}
MessageBox.Show(sb.ToString());