繁体   English   中英

移动到LINQ到XML C#的节点值?

[英]moving to a node values in linq to xml C#?

我正在尝试在C#中的author节点下获取电子邮件值。 但是什么都没有。 我的代码是=

XDocument xDoc = XDocument.Parse("myxml");
var foos = from xelem in xDoc.Descendants("author")
               select xelem.Element("email").Value;

我正在使用的XML是-

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:batch="http://schemas.google.com/gdata/batch" 

xmlns:gContact="http://schemas.google.com/contact/2008" xmlns:gd="http://schemas.google.com/g/2005" 

xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">
 <id>yogeshcp13@gmail.com</id>
 <updated>2015-02-09T04:03:31.220Z</updated>
 <category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#contact"/>
 <title type="text">Yogesh Adhikari's Contacts</title>
 <link rel="alternate" type="text/html" href="https://www.google.com/"/>
 <link rel="next" type="application/atom+xml" href="https://www.google.com/m8/feeds/contacts/yogeshcs2003%40gmail.com/full?max-

results=1&amp;start-index=2"/>
 <author>
  <name>Yogesh Adhikari</name>
  <email>yogeshcp13@gmail.com</email>
 </author>
 <generator version="1.0" uri="http://www.google.com/m8/feeds">Contacts</generator>
 <openSearch:totalResults>3099</openSearch:totalResults>
 <openSearch:startIndex>1</openSearch:startIndex>
 <openSearch:itemsPerPage>1</openSearch:itemsPerPage>
</feed>

有人可以指出出什么问题吗? 谢谢

获取后代时,需要指定名称空间以及名称。

XDocument xDoc = XDocument.Parse("myxml");
string ns = xDoc.Root.Name.Namespace;

var foos = from xelem in xDoc.Descendants(ns + "author")
           select xelem.Element(ns + "email").Value;

另外,您可以通过获取所有后代的枚举,然后按LocalName进行过滤,找到您的节点。 如果email仅是架构中author的一个节点,则还可以避免不必要的步骤来从author节点进行深入author ,而直接找到您的email节点:

var foos = xdoc.Descendants().Where(e => e.Name.LocalName == "email");
XDocument xDoc = XDocument.Load("myxml.xml");
var foos = xDoc.Descendants().Where(e => e.Name.LocalName == "email");
Console.WriteLine(foos.FirstOrDefault().Value);

如果要引用xml文件,请使用Load方法,否则解析应该没问题。 如果不使用特定路径,还请确保xml与二进制文件的文件夹一起存储。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM