2

我使用三种 XML 文件:

A型:

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

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 第二个问题是我如何从同一标签中的“值”获取值???

谢谢

4

6 回答 6

3

这篇文章:

//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
于 2013-03-28T19:23:57.650 回答
1

I would suggest using XPath. Here's an example where I read in the XML content from a locally stored string and select whatever the first node under the root is:

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

XmlNode node = doc.SelectSingleNode("(/*)");
于 2013-03-28T19:29:31.417 回答
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.
}
于 2013-03-28T19:44:44.247 回答
0

使用 Linq to XML 是在 .NET 中使用 XML 的最新和最强大的方法,它为您提供比 XmlDocument 和 XmlNode 等更多的功能和灵活性。

获取根节点非常简单:

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

一旦构建了 XDocument,就不需要使用任何 LINQ 查询或特殊检查。您只需从 XDocument 中提取 Root 属性。

于 2013-03-28T19:49:49.250 回答
0

谢谢我已经解决了第一部分

   XmlDocument xmlDoc = new XmlDocument();
   xmlDoc.Load(nomear);
   XmlNodeList ml = xmlDoc.GetElementsByTagName("*");
   XmlNode primer = xmlDoc.DocumentElement;
   exti = primer.Name;  
于 2013-03-28T20:01:32.440 回答
0

首先,要清楚,你问的是 root element,而不是 root node

您可以使用 XmlReader 来避免将大型文档完全加载到内存中。请参阅我对如何在https://stackoverflow.com/a/60642354/1307074上找到根元素的回答。

其次,一旦阅读器引用了元素,您可以使用阅读器的Name属性来获取元素的限定标签名称。Value您可以使用该属性将值作为字符串获取。

于 2020-03-11T18:31:19.123 回答