使用XPath访问XML元素(是:好教程学习的XPath) [英] Using XPATH to access XML elements (was: Good tutorial to learn xpath)
问题描述
我努力学习的XPath。该理论似乎非常简单,除了事实,这是行不通的。
I am trying to learn XPath. The theory seems extremely simple, except for the fact that it doesn't work.
我试图让每一个目标元素
I am trying to get the content of every target element
XPathDocument doc = new XPathDocument(sPath);
XPathNavigator nav = doc.CreateNavigator();
XPathExpression expr;
expr = nav.Compile("/doc/file/body/trans-unit/target");
XPathNodeIterator iterator = nav.Select(expr);
while (iterator.MoveNext())
{
XPathNavigator nav2 = iterator.Current.Clone();
sbDoc.Append(nav2.InnerXml);
}
的XML文档看起来是这样的:
The XML doc looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<doc version="1.2">
<file original="affiliate.php" source-language="EN-US" target-language="FR-FR" datatype="php">
<header>
<skl>
<external-file href="affiliate.php"/>
</skl>
</header>
<body>
<trans-unit id="tu1">
<source xml:lang="EN-US">Your Program Details</source>
<target xml:lang="FR-FR">Your Program Details</target>
</trans-unit>
<trans-unit id="tu2">
<source xml:lang="EN-US">Status</source>
<target xml:lang="FR-FR">Status</target>
</trans-unit>
这是几乎从教程一字,但我不能得到它的工作。在创建迭代器,在调试模式下,我可以看到,该文件被加载,但迭代器没有发现结果并跳过while循环。
This is nearly word for word from a tutorial, but I can't get it to work. When the iterator is created, in debug mode, I can see that the document is loaded, but iterator finds no result and skips the While loop.
我可能做的事情愚蠢至极,但什么?
I am probably doing something extremely stupid, but what?
任何人都知道在哪里可以找到一个良好的,可靠的XPath教程?
Anyone knows where I can find a good, reliable XPATH tutorial?
感谢所有。原来我忽略了一个事实,有一个命名空间(同时简化了XML代码,我除去我没有意识到这一点很重要),并增加了一个命名空间管理,代码工作正常。
Thanks all. Turns out I ignored the fact that there was a namespace (which I removed while simplifying the XML code as I didn't realize it was important), and with the addition of a namespace manager, the code works fine.
我现在正在研究提出的XPATH教程和他们好看。
I am now studying the XPATH tutorials proposed and they look good.
推荐答案
也许XML是不是你贴一个,但有一个默认命名空间声明。这是最主要的原因,初学者编写的XPath表达式不选择他们想要什么选择。您将需要一个XmlNamespaceManager的 http://msdn.microsoft.com/en-us/library/6k4x060d.aspx 在这种情况下。
Maybe the XML is not the one you posted but has a default namespace declaration. That is the main reason why XPath expressions written by beginners don't select what they want to select. You would need an XmlNamespaceManager http://msdn.microsoft.com/en-us/library/6k4x060d.aspx in that case.
这篇关于使用XPath访问XML元素(是:好教程学习的XPath)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!