获得使用LINQ XML节点 [英] Getting an XML node using LINQ

查看:128
本文介绍了获得使用LINQ XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知何故,使用LINQ我不能在开始这个CUF现场测试吧:

Somehow, using linq I can't test it with this CUF field in the beginning:

<NFe>
    <infNFe versao="1.0" Id="NFe0000000000">
        <ide>
             <cUF>35</cUF>
             <!--...-->
        </ide>
    </infNFe>
</NFe>

通过以​​下code:

With the following code:

XDocument document = XDocument.Load(@"c:\nota.xml");
            var query = from NFe in document.Descendants("NFe")
                        select new
                        {
                            cuf = NFe.Element("infNFe").Element("ide").Element("cUF").Value
                        };

整个XML加载到文档(检查),但NFe.cuf给我什么。我猜节点内部的参数搞乱起来。

The whole XML loads into document (checked) but NFe.cuf gives me nothing. I guess the parameters inside the nodes are messing it up..

我如何得到这个CUF与LINQ?
如果我想的Id参数infNFe?

How do I get this "cuf" with linq?
What if I wanted the Id parameter in infNFe ?

- -

我忘了给傻URL的开始,什么情况是,它的命名空间(不显示在Firefox中的XML命名空间的贡献)

I had forgotten to give the "silly url in the beginning", what happens is that it is the NAMESPACE, (the non-displaying of the namespace of the xml in Firefox contributed)

现在这样工作的:

        XNamespace ns = "http://www.portalfiscal.inf.br/nfe";
        XElement root = XElement.Load(@"c:\nota.xml");

        textBox1.Text = root.Element(ns + "infNFe").Element(ns + "ide").Element(ns + "cUF").Value;

有没有一种方法来设置命名空间的地方,而不是需要把它在每一个外地电话?

Is there a way to set the namespace somewhere, and not needing to put it in every single field call ?

推荐答案

您并不真正需要的是完整的LINQ查询 - 单一的单行会做:

You don't really need that full LINQ query - a single one-liner will do:

string cuf = document.Root.Element("infNFe").Element("ide").Element("cUF").Value;
// cuf = 35

同为ID:

string id = document.Root.Element("infNFe").Attribute("Id").Value;
// id = NFe0000000000

这篇关于获得使用LINQ XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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