簡體   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