使用 C# 读取 XML 文件不适用于某些 xml 文件

Axen_Rangs

我需要阅读以下 xml 文件。我使用过 XML 和 LINQ,但它们都没有显示任何值。我在代码上找不到任何错误。我已经关注了这个例子,它与那里显示的 XML 一起工作得很好。

<dataSet>
<transactions>
<trans>1</trans>
<Amount>1000</Amount>
<Name>1000</Name>
<Type>Income</Type>
<Date>2022-04-21T00:00:00+05:30</Date>
</transactions>
</dataSet>

我用过这段代码。

using System;
using System.Xml;

namespace ReadXMLInCsharp
{
    class Program
    {
        static void Main(string[] args)
        {
            //create XMLDocument object
            XmlDocument xmlDoc = new XmlDocument();

            //returns url of main directory which contains "/bin/Debug"
            var url = System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

            //correction in path to point it in Root directory
            var mainpath = ("F:\\Education\\Test\\new.xml");
            //load xml file
            xmlDoc.Load(mainpath);

            XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("/dataSet/transactions");

            
            var NodeStr = "";

            foreach (XmlNode node in nodeList)
            {
                NodeStr = NodeStr + "\nTransaction " + node.SelectSingleNode("trans").InnerText;
               


            }
            Console.WriteLine(NodeStr);
        }
    }
}
克里斯·斯特里克兰

您的 xml DataSet 节点具有命名空间属性,因此您需要删除它或使用 XmlNamespaceManager 来处理它。这是两者的小提琴:

https://dotnetfiddle.net/EOXtBN

首先,我将 xml 加载到一个字符串中,然后使用 .Replace:

xmlDoc.LoadXml(getXML().Replace(" xmlns='tempuri.org/DataSet.xsd'", ""));

可能不是最优的,因为该名称空间可能是有原因的,但这可能是您的一个选择。这是我要先工作的那个。

其次,我使用 XmlNamespaceManager 来处理解析。它不会增加那么多开销:

xmlDoc.LoadXml(getXML());
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ns", "tempuri.org/DataSet.xsd");
        
nodeList = xmlDoc.DocumentElement.SelectNodes("//ns:DataSet//ns:transactions", nsmgr); 
foreach (XmlNode node in nodeList) {
  NodeStr = NodeStr + "\nTransaction " + node.SelectSingleNode("ns:trans", nsmgr).InnerText;       
}

另外,请记住,您可以只在节点列表的 xpath 中包含 ns:trans,如下所示:

nodeList = xmlDoc.DocumentElement.SelectNodes("//ns:DataSet//ns:transactions//ns:trans", nsmgr); 
foreach (XmlNode node in nodeList) {
  NodeStr = NodeStr + "\nTransaction " + node.InnerText;       
}
Console.WriteLine(NodeStr);

你也可以使用 += 来清理它:

nodeList = xmlDoc.DocumentElement.SelectNodes("//ns:DataSet//ns:transactions//ns:trans", nsmgr); 
foreach (XmlNode node in nodeList) {
  NodeStr += "\nTransaction " + node.InnerText;       
}
Console.WriteLine(NodeStr);

让我知道这是否适合您。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章