[英]How to get text inside an XmlNode
如何获取 XmlNode 中的文本? 见下文:
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
}
而我最终想要做的是在每个节点的文本前面加上“帮助:”。
最简单的方法可能是遍历节点的所有直接子节点(使用ChildNodes
)并测试每个节点的NodeType
以查看它是Text
还是CDATA
。 不要忘记可能有多个文本节点。
foreach (XmlNode child in node.ChildNodes)
{
if (child.NodeType == XmlNodeType.Text ||
child.NodeType == XmlNodeType.CDATA)
{
string text = child.Value;
// Use the text
}
}
(仅供参考,如果您可以使用 .NET 3.5、LINQ 到XML更好用。)
在节点的子节点中搜索NodeType
为Text
的节点,并使用该节点的Value
属性。
请注意,您还可以使用text()
节点类型测试 select 文本节点与 XPath。
您可以读取 xmlnode 读取node.InnerText
的 InnerText 属性
检查这个
你也可以检查你写“阅读器”时得到的选项。
xml 文件
<?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>
和读者真的很基本但很快
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.