문제

이 질문이 이전에 비슷한 방식으로 묻는 것을 알고 있지만,이 일을 얻는 것 같습니다.

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> 
.

및 저는 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!
.

그러나 루트 노드의 간단한 선택조차도 null을 반환합니다!나는 내 네임 스페이스에 문제가 있는지 확신합니다.누군가 도움을 줄 수 있습니까?

이상적으로 XML 파일에서 값을 선택할 수있는 간단한 선을 원합니다.

String a = xmlDoc.SelectSingleNode(@"/Research/Product/Content/Title").Value;
.

btw, XML 파일 콘텐츠를 통해 (직접) 제어가 없습니다.

도움이 되었습니까?

해결책

I don't believe you can use an empty namespace alias and have it used automatically by the XPath expression. As soon as you use an actual alias, it should work though. This test is fine, for example:

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);
    }
}

Do you have to use XPath and XPathDocument, by the way? I tend to find that LINQ to XML is a much more pleasant API, particularly when it comes to namespaces. If you're using .NET 3.5 and you have no particular requirement to use XPath, I'd suggest you check it out.

다른 팁

Make the following changes

nsMgr.AddNamespace("x", "http://www.rixml.org/2005/3/RIXML"); 
XPathNavigator result = nav.SelectSingleNode("/x:Research", nsMgr);

i could post, and answer my own question, for the native equivalent of this code. Instead i'll just add it as an answer to the end.

When using the native IXMLDOMDocument (version 6) object:

//Give the default namespace as alias of "x"
document.setProperty("SelectionNamespaces","xmlns:x='http://www.rixml.org/2005/3/RIXML'");

//Query for the nodes we want
document.selectSingleNode("/x:Research");

Bonus Question: Why, oh why, does no Xml Document object model query the default namespace when no namespace is specified... sigh

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top