首页 文章

如何解析XML文件? [关闭]

提问于
浏览
492

有一种在C#中解析XML文件的简单方法吗?如果是这样,什么?

12 回答

  • 23

    使用XmlTextReaderXmlReaderXmlNodeReaderSystem.Xml.XPath命名空间 . 并且(XPathNavigatorXPathDocumentXPathExpressionXPathnodeIterator) .

    通常XPath使得阅读XML更容易,这正是您可能正在寻找的 .

  • 2

    这很简单 . 我知道这些是标准方法,但您可以创建自己的库来更好地处理 .

    这里有些例子:

    XmlDocument xmlDoc= new XmlDocument(); // Create an XML document object
    xmlDoc.Load("yourXMLFile.xml"); // Load the XML document from the specified file
    
    // Get elements
    XmlNodeList girlAddress = xmlDoc.GetElementsByTagName("gAddress");
    XmlNodeList girlAge = xmlDoc.GetElementsByTagName("gAge"); 
    XmlNodeList girlCellPhoneNumber = xmlDoc.GetElementsByTagName("gPhone");
    
    // Display the results
    Console.WriteLine("Address: " + girlAddress[0].InnerText);
    Console.WriteLine("Age: " + girlAge[0].InnerText);
    Console.WriteLine("Phone Number: " + girlCellPhoneNumber[0].InnerText);
    

    此外,还有一些other methods可以使用 . 例如,here . 我认为没有一种最好的方法可以做到这一点;你总是需要自己选择,最适合你的是什么 .

  • 289

    我刚刚被要求处理一个涉及解析XML文档的应用程序,我同意Jon Galloway的观点,在我看来,基于LINQ to XML的方法是最好的 . 然而,我确实需要挖掘一些可用的例子,所以不用多说,这里有几个!

    任何评论都欢迎,因为这段代码有效,但可能不完美,我想了解更多有关为此项目解析XML的信息!

    public void ParseXML(string filePath)  
    {  
        // create document instance using XML file path
        XDocument doc = XDocument.Load(filePath);
    
        // get the namespace to that within of the XML (xmlns="...")
        XElement root = doc.Root;
        XNamespace ns = root.GetDefaultNamespace();
    
        // obtain a list of elements with specific tag
        IEnumerable<XElement> elements = from c in doc.Descendants(ns + "exampleTagName") select c;
    
        // obtain a single element with specific tag (first instance), useful if only expecting one instance of the tag in the target doc
        XElement element = (from c in doc.Descendants(ns + "exampleTagName" select c).First();
    
        // obtain an element from within an element, same as from doc
        XElement embeddedElement = (from c in element.Descendants(ns + "exampleEmbeddedTagName" select c).First();
    
        // obtain an attribute from an element
        XAttribute attribute = element.Attribute("exampleAttributeName");
    }
    

    通过这些函数,我能够解析XML文件中的任何元素和任何属性都没有问题!

  • 44

    您可以使用XmlDocument并从Linq到XML类的属性中操作或检索数据 .

  • 16

    如果您正在处理大量数据(许多兆字节),那么您希望使用 XmlReader 来流式解析XML .

    如果保留完整生成的对象图,则其他任何内容( XPathNavigatorXElementXmlDocument 甚至 XmlSerializer )都将导致high memory usage,并且加载时间也非常慢 .

    当然,如果你需要内存中的所有数据,那么你可能没有太多选择 .

  • 6

    我不确定是否存在“解析XML的最佳实践” . 有许多技术适合不同的情况 . 使用哪种方式取决于具体情况 .

    您可以使用LINQ to XMLXmlReaderXPathNavigator或甚至正则表达式 . 如果你详细说明了你的需求,我可以尝试提出一些建议 .

  • 5

    您可以使用此库 System.Xml.Linq 解析XML . 下面是我用来解析XML文件的示例代码

    public CatSubCatList GenerateCategoryListFromProductFeedXML()
    {
        string path = System.Web.HttpContext.Current.Server.MapPath(_xmlFilePath);
    
        XDocument xDoc = XDocument.Load(path);
    
        XElement xElement = XElement.Parse(xDoc.ToString());
    
    
        List<Category> lstCategory = xElement.Elements("Product").Select(d => new Category
        {
            Code = Convert.ToString(d.Element("CategoryCode").Value),
            CategoryPath = d.Element("CategoryPath").Value,
            Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category
            SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category
        }).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList();
    
        CatSubCatList catSubCatList = GetFinalCategoryListFromXML(lstCategory);
    
        return catSubCatList;
    }
    
  • 2

    如果您使用的是.NET 2.0,请尝试 XmlReader 及其子类 XmlTextReaderXmlValidatingReader . 它们提供快速,轻量级(内存使用等),仅向前解析XML文件的方法 .

    如果您需要XPath功能,请尝试 XPathNavigator . 如果您需要内存中的整个文档,请尝试 XmlDocument .

  • 5

    使用好的XSD Schema创建一组带有xsd.exe的类,并使用XmlSerializer从XML中创建对象树,反之亦然 . 如果您对模型的限制很少,您甚至可以尝试使用Xml * Attributes在模型类和XML之间创建直接映射 .

    MSDN上有an introductory article about XML Serialisation .

    性能提示:构建 XmlSerializer 非常昂贵 . 如果要解析/写入多个XML文件,请保留对 XmlSerializer 实例的引用 .

  • 0

    您可以使用ExtendedXmlSerializer来序列化和反序列化 .

    Instalation 您可以从nuget安装ExtendedXmlSerializer或运行以下命令:

    Install-Package ExtendedXmlSerializer
    

    Serialization:

    ExtendedXmlSerializer serializer = new ExtendedXmlSerializer();
    var obj = new Message();
    var xml = serializer.Serialize(obj);
    

    Deserialization

    var obj2 = serializer.Deserialize<Message>(xml);
    

    Standard XML Serializer in .NET is very limited.

    • 不支持带循环引用的类的序列化或带有interface属性的类,

    • 不支持词典,

    • 没有用于读取旧版XML的机制,

    • 如果要创建自定义序列化程序,则您的类必须从IXmlSerializable继承 . 这意味着您的 class 将不是POCO class ,

    • 不支持IoC .

    ExtendedXmlSerializer can do this and much more.

    ExtendedXmlSerializer支持 .NET 4.5 或更高版本以及 .NET Core . 您可以将它与WebApi和AspCore集成 .

  • 0

    如果您使用的是.NET 3.5或更高版本,我会使用LINQ to XML .

  • 232

    另外,您可以通过以下方式使用XPath选择器(选择特定节点的简便方法):

    XmlDocument doc = new XmlDocument();
    doc.Load("test.xml");
    
    var found = doc.DocumentElement.SelectNodes("//book[@title='Barry Poter']"); // select all Book elements in whole dom, with attribute title with value 'Barry Poter'
    
    // Retrieve your data here or change XML here:
    foreach (XmlNode book in nodeList)
    {
      book.InnerText="The story began as it was...";
    }
    
    Console.WriteLine("Display XML:");
    doc.Save(Console.Out);
    

    the documentation

相关问题