为什么使用了'xmlns'属性影响的XPath查询节点? [英] Why does the 'xmlns' attribute affect XPath Node lookup?

查看:121
本文介绍了为什么使用了'xmlns'属性影响的XPath查询节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码运行完美。见下面的XML文件

 的XPathDocument xPathDoc =新的XPathDocument(@C:\Authors.xml); 
XPathNavigator的导航= xPathDoc.CreateNavigator();
声明XPathNodeIterator迭代器= navigator.Select(/联系人/作者/名字);
iterator.MoveNext();
串的firstName = iterator.Current.InnerXml;
Console.WriteLine(名字);



中的firstName'返回'乔',这是完美的价值。然而,当我这个attibute的xmlns =http://www.w3.org/1999/xhtml添加到''的标签,以便它看起来如下:

 <作者的xmlns =http://www.w3.org/1999/xhtml> 



然后代码不返回正确的值('乔')
为什么那么属性的xmlns =http://www.w3.org/1999/xhtml影响上面的代码和我缺少什么返回正确的价值?



任何帮助。将不胜感激。



下面是XML文件:

  < XML版本=1.0编码=UTF-8>?; 
<联系和GT;
<作者>
<&名字GT;乔< /姓>
< /作者>
<教师与GT;
<&名字GT;拉里< /姓>
< /教师>

<&画家GT;
<&名字GT;&玛丽LT; /姓>
< /画家>
< /联系和GT;


解决方案

的xmlns是用于避免标记之间冲突的命名空间的XML。情况下,当一个应用程序是使用XML从多个来源和相同的标记名存在于两个或多个XML文件。由于这样的歧义的概率与高时,命名空间是用来减少它


The following code works perfect. See XML file below.

XPathDocument xPathDoc = new XPathDocument(@"C:\Authors.xml");
XPathNavigator navigator = xPathDoc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("/Contacts/Author/FirstName");
iterator.MoveNext();
string firstName = iterator.Current.InnerXml;
Console.WriteLine(firstName);

The value of 'firstName' returns 'Joe' which is perfect. However, when I add this attibute xmlns="http://www.w3.org/1999/xhtml" to the '' tag, so that it looks as follows:

<Author xmlns="http://www.w3.org/1999/xhtml">

then the code does not return the correct value ('Joe') Why then the attribute xmlns="http://www.w3.org/1999/xhtml" affects the code above and what am I missing to return the correct value?

Any help will be greatly appreciated.

Here is the xml file:

<?xml version="1.0" encoding="UTF-8" ?> 
<Contacts>
<Author>
<FirstName>Joe</FirstName>
</Author>
<Teacher>
<FirstName>Larry</FirstName>
</Teacher>

<Painter>
<FirstName>Mary</FirstName>
</Painter>
</Contacts>

解决方案

xmlns is namespace which is used to avoid conflict between tags of the xml. Scenario, when one app is using xml from multiple sources and same tagname exist in two or more xml files. Since probablity of such ambiguity is high, namespace is used to reduce it.

这篇关于为什么使用了'xmlns'属性影响的XPath查询节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆