如何阅读此文件(xml 格式但具有另一个扩展名)

How to read this file (is xml formated but with another extension)

我有一个文件,它有一个 xml 结构,但有另一个扩展名 (.qlic)。我需要阅读它以获取 属性 UserCount,此值位于许可证标签内。 这是文件中的代码:

    <License xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" UserCount="542">
<OrganizationName>**********</OrganizationName>
<ServerName>******</ServerName>
<Servers />
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>Itavzm993LQxky+HrtwpJmQQSco=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>j7VVqrjacSRBgbRb1coGK/LQFRFWv9Tfe5y5mQmYM9HJ8EoKGtigOycoOPdCeIaIctVGT3rrgTW+2KcVmv92LTdpu7eC3QJk2HZgqRFyIy+HR9XQ9qYPV8sLLxVkkESvG19zglX66qkBJsm2UL6ps3BhnEt/jrs+FEsAeCBzM6s=</SignatureValue>
</Signature>
</License>

这是我尝试读取文件时的异常:"{"<License xmlns=''> was not expected."}"

这是我的 C# 代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.Serialization;

namespace xmlReader
{
    [XmlRoot(ElementName = "License"), XmlType("Licence")]
    public class ReaderXML
    {
        public ReaderXML()
        { 
        }

        public class result
        {
            public string _result;
        }

        public static void ReadXML()
        {
            XmlSerializer reader = new XmlSerializer(typeof(result));
            StreamReader file = new StreamReader(@"C:\Users\User\Desktop\myfile.qlic");
            result overview = new result();
            overview = (result)reader.Deserialize(file);

            Console.WriteLine(overview._result);

        }
    }

}

错误是由于缺少 XML 文件顶部的 XML 声明:

<?xml version='1.0' encoding='UTF-8'?>

XML 解析器期望该声明存在,因此错误消息 "{"<License xmlns=''> was not expected."}"

如果没有这个,它只是一个具有类似 XML 结构的文本文件。尝试在 XML 文件的最顶部添加该行,看看它是否修复了这个错误。

使用 Linq Xml 您查询属性 UserCount 的任务可以这么简单:

using (var reader = new StreamReader(@"C:\Users\User\Desktop\myfile.qlic"))
{
    XDocument lic = XDocument.Load(reader);
    string usercount = lic.Element("License").Attribute("UserCount").Value;
}

.Element(name) 将 return 只是具有给定名称的第一个元素。

在 MSDN 上查看 LINQ to Xml

如果您仍然需要反序列化问题中显示的 Xml,您为 XmlSerializer 指定的类型需要具有匹配的属性。

它还可以具有其他属性,您可以使用 [XmlIgnore] 属性进行标记。