Sim*_*eep 38 c# xml xpath linq-to-xml
如何从XDocument获取NameTable?
它似乎没有XmlDocument具有的NameTable属性.
编辑:从缺乏答案来判断,我猜我可能会忽略这一点.
我正在对像这样的XDocument进行XPath查询...
document.XPathSelectElements("//xx:Name", namespaceManager);
Run Code Online (Sandbox Code Playgroud)
它工作正常,但我必须手动将我想要使用的命名空间添加到XmlNamespaceManager,而不是像使用XmlDocument一样从XDocument中检索现有的命名表.
Ant*_*nes 29
您需要通过XmlReader推送XML并使用XmlReader的NameTable属性.
如果你已经有Xml加载到XDocument中,那么请确保使用XmlReader加载XDocument: -
XmlReader reader = new XmlTextReader(someStream);
XDocument doc = XDocument.Load(reader);
XmlNameTable table = reader.NameTable;
Run Code Online (Sandbox Code Playgroud)
如果您使用XDocument从头开始构建Xml,则需要调用XDocument的CreateReader方法,然后让某些内容消耗读者.一旦使用了阅读器(比如加载另一个XDocument但更好的是有些什么东西不会导致读者通过XDocument的内容)你可以检索NameTable.
Mat*_*ott 23
我是这样做的:
//Get the data into the XDoc
XDocument doc = XDocument.Parse(data);
//Grab the reader
var reader = doc.CreateReader();
//Set the root
var root = doc.Root;
//Use the reader NameTable
var namespaceManager = new XmlNamespaceManager(reader.NameTable);
//Add the GeoRSS NS
namespaceManager.AddNamespace("georss", "http://www.georss.org/georss");
//Do something with it
Debug.WriteLine(root.XPathSelectElement("//georss:point", namespaceManager).Value);
Run Code Online (Sandbox Code Playgroud)
马特
我必须手动将我想要使用的命名空间添加到XmlNamespaceManager,而不是像使用XmlDocument一样从XDocument中检索现有的命名表.
XDocument project = XDocument.Load(path);
//Or: XDocument project = XDocument.Parse(xml);
var nsMgr = new XmlNamespaceManager(new NameTable());
//Or: var nsMgr = new XmlNamespaceManager(doc.CreateReader().NameTable);
nsMgr.AddNamespace("msproj", "http://schemas.microsoft.com/developer/msbuild/2003");
var itemGroups = project.XPathSelectElements(@"msproj:Project/msproj:ItemGroup", nsMgr).ToList();
Run Code Online (Sandbox Code Playgroud)