如何使用Linq从具有命名空间的XML加载和访问XML数据 [英] How to Load and access data with Linq to XML from XML with namespaces

查看:95
本文介绍了如何使用Linq从具有命名空间的XML加载和访问XML数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在上一个问题中,我不知道如何解决我的问题. Linq to XML,如何在C#中访问元素? 这是我需要解析的XML:

In my previous question here, I didn’t understand how to solve my problem. Linq to XML, how to acess an element in C#? Here is my XML I need to parse:

<root>
         <photo>/filesphoto.jpg</photo>
         <photo:mtime>12</photo:mtime>
         <text>some text</text>
 </root>

要访问该元素,请使用以下代码:

To access the element I use this code:

var doc = XDocument.Parse(xml.Text);
doc.Descendants("text").FirstOrDefault().Value;

如何访问? 我已经尝试 http://aspnetgotyou.blogspot.com /2010/06/xdocument-or-xelement-with-xmlnamespace.html , 但是它被忽略了<photo:mtime>,我需要访问它. 请写一些代码.

How can I access ? I have try http://aspnetgotyou.blogspot.com/2010/06/xdocument-or-xelement-with-xmlnamespace.html, But it is ignored <photo:mtime> and I need to access it. Please write some code.

推荐答案

与@BrokenGlass的注释相反,您的XML无效.实际上,您在问题中提供的链接中的技术(用于加载名称空间)效果很好.也许您只是没有根据自己的需要更改示例.这是将带有名称空间的 xml片段解析为XElement的更紧凑的概括:

Contrary to @BrokenGlass' comments, your XML is not invalid. In fact the technique in the link you provided in your question (for loading namespaces) works fine. Maybe you just didn't change the example for your own needs. Here's a more compact generalization for parsing xml fragments with namespaces into an XElement:

public static XElement parseWithNamespaces(String xml, String[] namespaces) {
    XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(new NameTable());
    foreach (String ns in namespaces) { nameSpaceManager.AddNamespace(ns, ns); }
    return XElement.Load(new XmlTextReader(xml, XmlNodeType.Element, 
        new XmlParserContext(null, nameSpaceManager, null, XmlSpace.None)));
}

使用您的准确输入:

string xml = 
@"<root>
    <photo>/filesphoto.jpg</photo>
    <photo:mtime>12</photo:mtime>
    <text>some text</text>
</root>";
XElement x = parseWithNamespaces(xml, new string[] { "photo" });
foreach (XElement e in x.Elements()) { 
    Console.WriteLine("{0} = {1}", e.Name, e.Value); 
}
Console.WriteLine(x.Element("{photo}mtime").Value);

打印:

photo = /filesphoto.jpg
{photo}mtime = 12
text = some text
12

这篇关于如何使用Linq从具有命名空间的XML加载和访问XML数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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