繁体   English   中英

XML文件的读取属性

[英]Reading attribute of an XML file

我有这个XML文件,我可以读取所有节点

<?xml version="1.0" encoding="UTF-8"?>
<cteProc xmlns="http://www.portalfiscal.inf.br/cte" versao="1.04">
    <CTe xmlns="http://www.portalfiscal.inf.br/cte">
        <infCte versao="1.04" ID="CTe3512110414557000014604"></infCte>
    </CTe>
</cteProc> 

我尝试使用C#阅读本文

string chavecte;        
string CaminhoDoArquivo = @"C:\Separados\13512004-procCTe.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CaminhoDoArquivo); //Carregando o arquivo
chavecte = xmlDoc.SelectSingleNode("infCTe")
                    .Attributes.GetNamedItem("Id").ToString();

但是这段代码有问题。

如果要使用Linq To Xml

var xDoc = XDocument.Load(CaminhoDoArquivo);
XNamespace ns = "http://www.portalfiscal.inf.br/cte";
var chavecte = xDoc.Descendants(ns+"infCte").First().Attribute("id").Value;

PS:我假设您的xml的无效行为

<infCte versao="1.04" id="CTe3512110414557000014604"></infCte>

更换

chavecte = xmlDoc.SelectSingleNode("infCTe").Attributes.GetNamedItem("Id").Value;

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ab", "http://www.portalfiscal.inf.br/cte");

chavecte = xmlDoc.SelectSingleNode("//ab:infCte", nsmgr)
                 .Attributes.GetNamedItem("Id").Value;

我还注意到infCte在您的xml中没有正确定义ID属性

另一个可能的解决方案是:

string CaminhoDoArquivo = @"C:\Separados\13512004-procCTe.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CaminhoDoArquivo); //Carregando o arquivo

// Select the node you're interested in
XmlNode node = xmlDoc.SelectSingleNode("/cteProc/CTe/infCte");
// Read the value of the attribute "ID" of that node
string chavecte = node.Attributes["ID"].Value;

暂无
暂无

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

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