我在使用 Linq To Xml 时遇到问题。
一个简单的代码。我有这个 XML:
<?xml version="1.0" encoding="utf-8" ?>
<data xmlns="http://www.example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/directory file.xsd">
<contact>
<name>aaa</name>
<email>email@email.ext</email>
<birthdate>2002-09-22</birthdate>
<telephone>000:000000</telephone>
<description>Description for this contact</description>
</contact>
<contact>
<name>sss</name>
<email>email@email.ext</email>
<birthdate>2002-09-22</birthdate>
<telephone>000:000000</telephone>
<description>Description for this contact</description>
</contact>
<contact>
<name>bbb</name>
<email>email@email.ext</email>
<birthdate>2002-09-22</birthdate>
<telephone>000:000000</telephone>
<description>Description for this contact</description>
</contact>
<contact>
<name>ccc</name>
<email>email@email.ext</email>
<birthdate>2002-09-22</birthdate>
<telephone>000:000000</telephone>
<description>Description for this contact</description>
</contact>
我想让每个联系人都将其映射到对象 Contact 上。为此,我使用了这段代码:
XDocument XDoc = XDocument.Load(System.Web.HttpRuntime.AppDomainAppPath + this.filesource);
XElement XRoot = XDoc.Root;
//XElement XEl = XElement.Load(this.filesource);
var results = from e in XRoot.Elements("contact")
select new Contact((string)e.Element("name"), (string)e.Element("email"), "1-1-1", null, null);
List<Contact> cntcts = new List<Contact>();
foreach (Contact cntct in results) {
cntcts.Add(cntct);
}
Contact[] c = cntcts.ToArray();
// Encapsulating element
Elements<Contact> final = new Elements<Contact>(c);
好吧,不要介意这一切:专注于此:
当我拿到根节点的时候就没事了,我拿对了。
当我使用 select 指令时,我试图让每个节点都说:from e in
XRoot.Elements("contact")
好的,问题来了:如果我使用:from e in XRoot.Elements(),我会得到所有的接触节点,但是如果我使用:from e in XRoot.Elements("contact"),我什么都得不到:Empty SET。
好的,你告诉我:使用另一个:好的,我这样做,让我们使用:
from e in XRoot.Elements()
,无论如何我都得到了所有节点,这是正确的,但这里出现了另一个问题:
当说:select new Contact((string)e.Element("name"), (string)e.Element("email"), "1-1-1", null, null);
我尝试访问 <name>, <email>
...我必须使用 .Element("name") 并且它也不起作用!!!!!!!!这到底是什么??????????看来我和我传递的名字不匹配但这怎么可能呢。我知道 Elements() 函数采用重载的一个参数,该参数是一个映射到字符串的 XName。请考虑我编写的代码来自一个示例,它应该可以工作。
最佳答案
非常简单:有一个 XML 命名空间在起作用,您忽略了它:
<data xmlns="http://www.example.com"
**************************
您需要将其添加到您的 Linq-to-XML 查询中!
类似于:
XNamespace ns = "http://www.example.com";
然后
XRoot.Elements(ns + "contact")
当然,在访问子元素时也使用 XML 命名空间:
var results = from e in XRoot.Elements("contact")
select new Contact(e.Element(ns + "name").Value,
e.Element(ns + "email").Value,
"1-1-1", null, null);
这应该有所帮助。请参阅 Working with XML Namespaces 上的 MSDN 文档了解更多详情。
关于c# - 使用 XElement 的方法 Elements(XName) 的 Linq To Xml 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2754458/