2013-01-02 101 views
-1

我有这样的XML文件的属性,我可以读取所有将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(); 

节点,但什么是错,此代码。

+0

你熟悉XML命名空间的概念? –

+0

您的XML示例缺少Id属性... –

+0

[在C#中使用带默认命名空间的Xpath]的可能重复(http://stackoverflow.com/questions/585812/using-xpath-with-default-namespace-in-c-尖锐) - 最有可能的原因是在选择“infCte”节点时缺少使用名称空间的问题。 –

回答

2

更换

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没有ID在你的XML

+1

由于XPath到“infCte”节点不包含“http://www.portalfiscal.inf.br/cte”命名空间,因此它不太可能提供帮助。 –

+0

@AlexeiLevenkov,对不起,当有人告诉你“它不起作用”时,有时很难找到所有原因。我会看看,然后进行编辑 –

4

属性正确定义如果你想使用LINQ 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> 
+0

感谢代码完美。我写错了,我忘了“id” –

+0

+1。为了获得正确的答案,特别是对于魔术般的知道@alejandrocarnero不关心使用哪些XML解析类。 –

0

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

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;