【发布时间】:2016-12-23 03:18:48
【问题描述】:
我在 C# 中有字符串,它具有以下内容
responseString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<lab:labs xmlns:lab=\"http://njjhjhjh/ri/lab\">\n <lab uri=\"https://dsdsdsds.org/api/v2/labs/1\">\n <name>Administrative Lab</name>\n </lab>\n</lab:labs>\n"
我希望将 uri 值 https://dsdsdsds.org/api/v2/labs/1 提取并存储在字符串中
string xmlString =responseString.Replace("lab:labs>", "labs>");
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
XmlNodeList nodes = doc.SelectNodes("labs//lab");
if (nodes != null && nodes.Count > 0)
{
XmlNode node = nodes[0];
if (node.Attributes["uri"] != null)
{
string return_uri = node.Attributes["uri"].Value.ToString();
}
}
但上面的代码会抛出类似{"The 'lab:labs' start tag on line 2 position 2 does not match the end tag of 'labs'. Line 6, position 3."} 的错误。有没有一种简单的方法来获取该 uri 值
【问题讨论】:
-
那是因为您正在破坏您的 XML。不要那样做;相反,请正确使用命名空间。
-
另外,使用
XDocument;好多了。
标签: c# xml xml-parsing