C# Xml Node to String
I have a XML do开发者_如何学Pythoncument 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?
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.
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.
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());
精彩评论