Rya*_*yan 3 .net c# xml namespaces searching-xml
我知道之前已经以类似的方式询问过这个问题,但我似乎无法让这个问题起作用.
我有一些xml:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<Research xmlns="http://www.rixml.org/2005/3/RIXML" xmlns:xalan="http://xml.apache.org/xalan" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" createDateTime="2011-03-29T15:41:48Z" language="eng" researchID="MusiJvs3008">
<Product productID="MusiJvs3008">
<StatusInfo currentStatusIndicator="Yes" statusDateTime="2011-03-29T15:41:48Z" statusType="Published" />
<Source>
<Organization type="SellSideFirm" primaryIndicator="Yes">
<OrganizationID idType="Reuters">9999</OrganizationID>
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用xpath读取值:
XPathDocument xmldoc = new XPathDocument(xmlFile);
XPathNavigator nav = xmldoc.CreateNavigator();
XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable);
nsMgr.AddNamespace(string.Empty, "http://www.rixml.org/2005/3/RIXML");
XPathNavigator result = nav.SelectSingleNode("/Research", nsMgr); // <-- Returns null!
Run Code Online (Sandbox Code Playgroud)
但即使是简单的根节点选择也会返回null!我确信我的命名空间有问题.有人可以帮忙吗?
理想情况下,我想要简单的线条,让我从xml文件中选择值,即
String a = xmlDoc.SelectSingleNode(@"/Research/Product/Content/Title").Value;
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我没有(直接)控制XML文件内容.
我不相信你可以使用一个空的命名空间别名,并让它由XPath表达式自动使用.只要你使用一个实际的别名,它应该工作.这个测试很好,例如:
using System;
using System.Xml;
using System.Xml.XPath;
class Test
{
static void Main()
{
string xmlFile = "test.xml";
XPathDocument xmldoc = new XPathDocument(xmlFile);
XPathNavigator nav = xmldoc.CreateNavigator();
XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable);
nsMgr.AddNamespace("x", "http://www.rixml.org/2005/3/RIXML");
XPathNavigator result = nav.SelectSingleNode("/x:Research", nsMgr);
Console.WriteLine(result);
}
}
Run Code Online (Sandbox Code Playgroud)
你必须使用XPath XPathDocument,顺便说一句吗?我倾向于认为LINQ到XML是一个多更愉快的API,特别是当它涉及到的命名空间.如果您使用的是.NET 3.5并且没有特别要求使用XPath,我建议您查看它.