2013-03-28 102 views
2

我具有三种XML文件工作:阅读来自XML第一根节点

A型:

<?xml version="1.0" encoding="UTF-8"?> 
<nfeProc versao="2.00" xmlns="http://www.portalfiscal.inf.br/nfe"> 
</nfeProc> 

Tyepe B:

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

类型C:]

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

我试着用这段代码读取第一个节点:

 XmlDocument xmlDoc = new XmlDocument(); 
    xmlDoc.Load(@"C:\crruopto\135120068964590_v01.04-procCTe.xml"); 
    XmlNodeList ml = xmlDoc.GetElementsByTagName("*"); 
    XmlElement root = xmlDoc.DocumentElement; 
    exti = root.ToString(); 

,但不返回任何我想要阅读的第一个节点,需要知道,如果该文件是nfeProc,canCTE或cteProc 第二个问题是如何在相同的代码得到“价值”的价值呢? ??

感谢

回答

3

this后:

//Root node is the DocumentElement property of XmlDocument 

XmlElement root = xmlDoc.DocumentElement 

//If you only have the node, you can get the root node by 

XmlElement root = xmlNode.OwnerDocument.DocumentElement 
0

我会建议使用XPath。这里就是我在从本地存储的字符串的XML内容阅读和选择任何根目录下的第一个节点是一个例子:

XmlDocument doc = new XmlDocument(); 
doc.Load(new StringReader(xml)); 

XmlNode node = doc.SelectSingleNode("(/*)"); 
0

如果你不使用XmlDocument的东西需要那么Linq是你的朋友。

XDocument doc = XDocument.Load(@"C:\crruopto\135120068964590_v01.04-procCTe.xml"); 
XElement first = doc.GetDescendants().FirstOrDefault(); 
if(first != null) 
{ 
    //first.Name will be either nfeProc, canCTE or cteProc. 
} 
0

使用LINQ合作,XML是.NET中使用XML的最新和最有力的方式,为您提供更多的权力和灵活性比之类的XmlDocument和XmlNode的。

获取根节点是非常简单的:

XDocument doc = XDocument.Load(@"C:\crruopto\135120068964590_v01.04-procCTe.xml"); 
Console.WriteLine(doc.Root.Name.ToString()); 

一旦你建立你不需要使用任何LINQ查询或特殊检查一个XDocument。您只需从XDocument中提取Root属性即可。

0

谢谢,我已经解决了这种方式,第一部分

XmlDocument xmlDoc = new XmlDocument(); 
    xmlDoc.Load(nomear); 
    XmlNodeList ml = xmlDoc.GetElementsByTagName("*"); 
    XmlNode primer = xmlDoc.DocumentElement; 
    exti = primer.Name;