How to get text inside an XmlNode
How do I get the text that is within an XmlNode? See below:
XmlNodeList nodes = rootNode.SelectNodes("descendant::*");
for (int i = 0; i < nodes.Count; i++)
{
XmlNode node = nodes.Item(i);
//TODO: Display only the text of only this node,
开发者_如何学运维 // not a concatenation of the text in all child nodes provided by InnerText
}
And what I ultimately want to do is preppend "HELP: " to the text in each node.
The simplest way would probably be to iterate over all the direct children of the node (using ChildNodes
) and test the NodeType
of each one to see if it's Text
or CDATA
. Don't forget that there may be multiple text nodes.
foreach (XmlNode child in node.ChildNodes)
{
if (child.NodeType == XmlNodeType.Text ||
child.NodeType == XmlNodeType.CDATA)
{
string text = child.Value;
// Use the text
}
}
(Just as an FYI, if you can use .NET 3.5, LINQ to XML is a lot nicer to use.)
Search the node's children for a node with NodeType
of Text
, and use the Value
property of that node.
Note that you can also select text nodes with XPath by using the text()
node-type test.
you can read the InnerText property of xmlnode
read node.InnerText
Check this
also you might check what options you get when you write "reader."
xml file
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<ISO_3166-1_List_en xml:lang="en">
<ISO_3166-1_Entry>
<ISO_3166-1_Country_name>SINT MAARTEN</ISO_3166-1_Country_name>
<ISO_3166-1_Alpha-2_Code_element>SX</ISO_3166-1_Alpha-2_Code_element>
</ISO_3166-1_Entry>
<ISO_3166-1_Entry>
<ISO_3166-1_Country_name>SLOVAKIA</ISO_3166-1_Country_name>
<ISO_3166-1_Alpha-2_Code_element>SK</ISO_3166-1_Alpha-2_Code_element>
</ISO_3166-1_Entry>
</ISO_3166-1_List_en>
and reader really basic but fast
XmlTextReader reader = new XmlTextReader("c:/countryCodes.xml");
List<Country> countriesList = new List<Country>();
Country country=new Country();
bool first = false;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
if (reader.Name == "ISO_3166-1_Entry") country = new Country();
break;
case XmlNodeType.Text: //Display the text in each element.
if (first == false)
{
first = true;
country.Name = reader.Value;
}
else
{
country.Code = reader.Value;
countriesList.Add(country);
first = false;
}
break;
}
}
return countriesList;
精彩评论