English 中文(简体)
XmlNode.SelectNodes的基础知识是什么?
原标题:
  • 时间:2009-03-30 21:51:56
  •  标签:

我不确定为什么这不起作用。

I have an XmlNode in a known-format. It is:

<[setting-name]>
    <dictionary>
       <[block-of-xml-to-process]/>
       <[block-of-xml-to-process]/>
       <[block-of-xml-to-process]/>
    </dictionary>
</[setting-name]>

I have a reference to the node in a variable called pattern. I want an iterable collection of nodes, each of which is represented by a [block-of-xml-to-process] above. The name and structure of the blocks is unknown at this point. [Setting-name] is known.

This seems pretty straightforward. I can think of a half-dozen XPATH expressions that should point to the blocks. I ve tried:

XmlNodeList kvpsList = pattern.SelectNodes(String.Format(@"/{0}/dictionary/*", _CollectionName));
XmlNodeList kvpsList = pattern.SelectNodes(String.Format(@"{0}/dictionary/*", _CollectionName));
XmlNodeList kvpsList = pattern.SelectNodes(@"//dictionary/*");
XmlNodeList kvpsList = pattern.SelectNodes(@"//dictionary");

但是,显然我缺乏对XPATH的基本理解或者某些.SelectNodes的特殊技巧,因为它们都没有稳定地发挥作用。

我做错了什么?

问题回答

你尝试过从你的XPath字符串中移除“@”吗?

XmlNodeList kvpsList = pattern.SelectNodes("//dictionary");

应该有效 - 对我来说每天都有效 :-)

马克 (Mǎkè)

你试过了吗?

XmlNodeList kvpsList = pattern.SelectNodes(@"//dictionary:child");

或者

XmlNodeList kvpsList = pattern.SelectNodes(@"/[setting-name]/dictionary:child");

Pretty much gets the children of "dictionary" If that doesnt work, does the actual call to dictionary work?

我遇到了同样的问题,似乎是一种已知的但是意料之外的行为。请参见Xml-SelectNodes with default-namespace via XmlNamespaceManager not working as expected

For example, I got it to work by instantiating a XmlNamespaceManager using the XmlDocument s NameTable, then added a namespace with an arbitrary name such as "a" associated with the NamespaceURI of the main document element. Note that the XmlDocument s NamespaceURI was blank in my case, but its DocumentElement s NameSpaceURI actually had a value. That s probably why it wouldn t work without specifying a namespace originally.

XmlDocument doc = new XmlDocument();
doc.Load( file.FullName );
XmlNode docElement = doc.DocumentElement as XmlNode;
XmlNamespaceManager nsman = new XmlNamespaceManager( doc.NameTable );
nsman.AddNamespace( "a", docElement.NamespaceURI );
docElement.SelectNodes( "a:wavetrack", nsman ); //docElement.SelectNodes("wavetrack") wasn t working

命名空间可能会引起问题吗?此外,请尝试查看“pattern.OuterXml”,以确保您正在查看正确的元素。

What is the use of variable pattern?
Is it a reference to the DOM of the entire XML?

See what this results into pattern.SelectNodes("//dictionary/").ChildNodes.Count

EDIT: Is this well-formed xml?

我刚刚在搜索这个东西,发现只要输入以下内容就可以:

XmlNodeList kvpsList = pattern.SelectNodes("dictionary");

kvpsList将包含所有[要处理的xml块],尽管我不知道为什么。=)





相关问题
热门标签