C# XmlDocument SelectNodes issue

本文介绍了解决XML文档中命名空间问题的方法,通过示例代码展示了如何使用.NET平台下的XmlNamespaceManager来正确选取带有命名空间的元素。

Hi all,

I have a very simple xspf file:

<?xml version="1.0"?>
<playlist version="1" xmlns="http://xspf.org/ns/0/">
<title>Easter Mix</title>
<info>This is our selection for the Easter period.</info>
<trackList>
<track>
<info>some info</info>
<creator>some creator</creator>
<title>a title</title>
<location>location1.mp3</location>
<image>some.jpg</image>
</track>
<track>
<info>some info</info>
<creator>some creator</creator>
<title>a title</title>
<location>location2.mp3</location>
<image>some.jpg</image>
</track>
</trackList>
</playlist>

I am trying to get the Title and Info elements at the top of the document using

xmldoc.SelectNodes("/playlist/title")

or

xmldoc.SelectSingleNode("/playlist/title")

But it just doesn't find it.Anybody knows how should I do it?

Many thanks

Not sure what language you are coding in but your problem is you have a namespace in your Xml and you are not querying the Xml using it. Here is some sample code that shows you how to add a namespace to solve the problem

XmlDocument xmldoc = new XmlDocument();

xmldoc.Load("Playlist.xml");
XmlNamespaceManager manager = new XmlNamespaceManager(xmldoc.NameTable);
manager.AddNamespace("xspf", "http://xspf.org/ns/0/");

string title = xmldoc.SelectSingleNode("//xspf:title", manager).InnerText
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值