获得使用LINQ XML节点节点、LINQ、XML

2023-09-06 08:49:52 作者:与君酌星尘

不知何故,使用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