Reputation: 141
I have a file, it has a xml structure but with another extension(.qlic). I need to read it to get the property UserCount, this value is inside a Licence tag. Here´s the code inside the file:
<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>
And here´s the exception when I'm trying to read the file: "{"<License xmlns=''> was not expected."}"
And here´s my c# code:
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);
}
}
}
Upvotes: 0
Views: 874
Reputation: 18061
Using Linq to Xml your task of querying the attribute UserCount
can be as simple as that:
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)
will return just the first element with the given name.
Check out LINQ to Xml on MSDN.
If you still need to deserialize the Xml shown in your question the type you specify for your XmlSerializer need to have the matching properties.
It can have other properties as well which you can mark with the [XmlIgnore]
attribute.
Upvotes: 1
Reputation: 1683
The error is due to missing the XML declaration at the top of your XML file:
<?xml version='1.0' encoding='UTF-8'?>
The XML parser expects that declaration to be there, hence the error message "{"<License xmlns=''> was not expected."}"
Without this, it's just a text file with an XML-like structure. Try adding that line at the very top of the XML file, and see if it fixes this error.
Upvotes: 0