【发布时间】:2020-04-01 09:22:53
【问题描述】:
我试图在加载 XML 文件后从节点获取内部文本。 我已经用另一个文件尝试了这段代码并且它有效。但是在这里我无法获取节点值。 谁能指出我做错了什么?
XML 文件 - restaurant_reviews.xml
<?xml version="1.0"?>
<restaurants xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.algonquincollege.com/onlineservice/reviews">
<restaurant>
<name>Laughing Man</name>
<logo>
<name>Visit the Laughing Man</name>
<imagefile>laughing-man.gif</imagefile>
<width unit="px">50</width>
<height unit="px">200</height>
</logo>
</restaurant>
<restaurant>
<name>Gong’s Asian Cuisine</name>
<logo>
<name/>
<imagefile>gong-asian-cuisine.gif</imagefile>
<width unit="px">150</width>
<height unit="px">250</height>
</logo>
</restaurant>
</restaurants>
C# 代码
List<string> names = new List<string>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(HttpContext.Current.Server.MapPath(@"~/App_Data/restaurant_reviews.xml"));
XmlNodeList nodes = xmlDoc.SelectNodes("/restaurants/restaurant");
foreach (XmlNode itemNode in nodes)
{
XmlNode titleNode = itemNode.SelectSingleNode("name");
if (titleNode != null)
{
names.Add(titleNode.InnerText);
}
}
【问题讨论】:
-
您的元素位于命名空间内,因此您需要使用
XmlNamespaceManager。看看stackoverflow.com/questions/30279306/… -
@Sean 谢谢你的朋友。这是主要问题。