I am trying to read XML document.
My XML:
<?xml version="1.0" encoding="utf-8"?>
<SplashScreen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Path>SplashScreen/Image-King</Path>
</SplashScreen>
My code which is reading XML:
XmlGameScreen = new XmlManager<GameScreen>();
XmlGameScreen.Type = currentscreen.Type;
currentscreen = XmlGameScreen.Load("LoadXML/SplashScreen.xml");
And
public Type Type;
public T Load(string path)
{
T instance;
using (TextReader textreader = new StreamReader(path))
{
XmlSerializer xml = new XmlSerializer(Type);
instance = (T)xml.Deserialize(textreader);
}
return instance;
}
I am getting error on instance = (T)xml.Deserialize(textreader);
Is my XML document wrong? I am trying to read <Path>
.
Update :
My Internal Exception:
Cannot serialize member 'MyRPGgame.SplashScreen._image'
of type 'Microsoft.Xna.Framework.Graphics.Texture2D'
asked Jan 12, 2015 at 15:59
Losser BadLosser Bad
2631 gold badge2 silver badges8 bronze badges
6
In my case it appears one of the Visual Studio 2017 version 15.5 updates caused this error when trying to open SSRS projects. The solution is to delete the *.rptproj.rsuser file from the project folder and try again.
answered Feb 27, 2018 at 13:26
user875318user875318
5664 silver badges11 bronze badges
7
My experience from it would be that in the 2nd line in the 2nd chararacter, there is an error.
have a look if your class names are different from the XML tags. are you maybe changing the «XML Root name» to a different one.
Have a look at the XML structure and which class are you serializing to which node.
Also, read the
MSDN Documentation about the XmlRootAttribute Class.
answered Jan 12, 2015 at 17:40
user853710user853710
1,7051 gold badge13 silver badges27 bronze badges
1
That usually means you have whitespace at the start of the file; check for a line-break before the <?xml...
. Even better: please show the first few bytes (preferably as far as <SplashScreen
) of the file as viewed in a binary editor.
It could also mean you have an invisible unicode or control character somewhere before the <SplashScreen
answered Jan 12, 2015 at 16:43
Marc GravellMarc Gravell
1.0m263 gold badges2555 silver badges2891 bronze badges
1
Just wanted to share what worked for me. I had a similar error
System.InvalidOperationException: There is an error in XML document (1, 40).
—> System.InvalidOperationException:<tsResponse xmlns='http://xxxyyyzzzz.com/api'>
was not expected.
I was trying to deserialize a string to an object of type tsResponse
.
After adding the following attribute [Serializable, XmlRoot(ElementName = "tsResponse", Namespace = "http://xxxyyyzzzz.com/api")]
to the class tsResponse
i was able to resolve my issue.
[Serializable, XmlRoot(ElementName = "tsResponse", Namespace = "http://xxxyyyzzzz.com/api")]
public class tsResponse
{
[XmlElement]
public CredentialsXml credentials { get; set; }
}
I.e had to add Namespace attribute (System.Xml.Serialization).
answered May 13, 2021 at 3:41
j4jadaj4jada
1849 bronze badges
Try this: When you are deserializing XML to List just add an extra
line to the start i.e ArrayOfAddressDirectory
as follows and don’t put any space at start and end of file.
<?xml version="1.0"?>
<ArrayOfAddressDirectory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AddressDirectory>
<Owner>MS. Dhoni</Owner>
<Age>48</Age>
<Company>India</Company>
</AddressDirectory>
</ArrayOfAddressDirectory>
Here is the C# code:
namespace XmlReadProgram
{
public class AddressDirectory
{
public string Owner { get; set; }
public string Age { get; set; }
public string Company { get; set; }
}
public class Program
{
static void Main(string[] args)
{
List<AddressDirectory> adlist = new List<AddressDirectory>();
using (FileStream fileStream = File.OpenRead(@"E:inputDirectoryaddress.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<AddressDirectory>));
adlist = (List<AddressDirectory>)serializer.Deserialize(fileStream);
}
//You can use foreach to print all data
Console.WriteLine(adlist[0].Owner);
Console.WriteLine(adlist[0].Age);
Console.WriteLine(adlist[0].Company);
}
}
}
tripleee
174k33 gold badges271 silver badges313 bronze badges
answered Aug 4, 2020 at 4:57
In my case, a property with [XmlArrayAttribute]
had the getter accessing a field with [XmlIgnoreAttribute]
that was left uninitialized.
answered Jan 30, 2020 at 13:32
The problem in your case it’s definitely the confusion between Type and template T. You are trying to construct Serializer with Type —> new XmlSerializer(Type) and then deserialize with template T —-> (T)xml.Deserialize. So the solution is to replace Type in constructing with typeof(T), and this should eliminate the initial XML document problem of (2, 2).
answered May 7, 2021 at 9:12
- Remove From My Forums
-
Question
-
User837036733 posted
I’m trying to Deserialize xml coming from an HttpWebResponse.
At the point of Deserializatoin, I get «There is an error in XML document (0, 0).»
Here’s my code to take the response and try shoving the stream into an XmlReader:
public static XmlReader GetResponseXmlReader(HttpWebResponse response) { Stream dataStream = null; // stream from WebResponse // Get the response stream dataStream = response.GetResponseStream(); XmlReader xmlReader = XmlReader.Create(dataStream); if (xmlReader == null) { throw new NullReferenceException("The XmlReader is null"); } return xmlReader; }
The xmlReader is then sent to my Deserialization Method:
public class Serializer
{
public static List<Album> CreateAlbumFromXMLDoc(XmlReader reader)
{
// Create an instance of a serializer var serializer = new XmlSerializer(typeof(Album));GetAlbumsResponse album = (GetAlbumsResponse)serializer.Deserialize(reader);
return album.Albums;
}
}When I look at the reader, I believe it doesn't have any xml data...I think. I mean it appears as though it does not.
There is definitely a valid Xml Doc in the response and here it is:
<?xml version="1.0" encoding="UTF-8"?> <photos_GetAlbums_response xmlns="http://api.xxx.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.xxx.com/1.0/ http://api.xxx.com/1.0/xxx.xsd" list="true"> <album> <aid>7321990241086938677</aid> <cover_pid>7031990241087042549</cover_pid> <owner>1124262814</owner> <name>Album Test 1</name> <created>1233469624</created> <modified>1233469942</modified> <description>Our trip</description> <location>CA</location> <link>http://www.xxx.com/album.php?aid=7733&id=1124262814</link> <size>48</size> <visible>friends</visible> </album> <album> <aid>231990241086936240</aid> <cover_pid>7042330241087005994</cover_pid> <owner>1124262814</owner> <name>Album Test 2</name> <created>1230437805</created> <modified>1233460690</modified> <description /> <location /> <link>http://www.xxx.com/album.php?aid=5296&id=1124262814</link> <size>34</size> <visible>everyone</visible> </album> <album> <aid>70319423341086937544</aid> <cover_pid>7032390241087026027</cover_pid> <owner>1124262814</owner> <name>Album Test 3</name> <created>1231984989</created> <modified>1233460349</modified> <description /> <location /> <link>http://www.xxx.com/album.php?aid=6600&id=1124262814</link> <size>3</size> <visible>friends</visible> </album> <album> <aid>703153403241086936188</aid> <cover_pid>7031993241087005114</cover_pid> <owner>1124262814</owner> <name>Album Test 4</name> <created>1230361978</created> <modified>1230362306</modified> <description>My Album</description> <location /> <link>http://www.xxx.com/album.php?aid=5244&id=1124262814</link> <size>50</size> <visible>friends</visible> </album> <album> <aid>70313434232086935881</aid> <cover_pid>70319902323087001093</cover_pid> <owner>1124262814</owner> <name>Album Test 5</name> <created>1229889219</created> <modified>1229889235</modified> <description>MiscPics</description> <location /> <link>http://www.xxx.com/album.php?aid=4937&id=1124262814</link> <size>1</size> <visible>friends-of-friends</visible> </album> <album> <aid>7031990234523935541</aid> <cover_pid>7031990231086996817</cover_pid> <owner>1124262814</owner> <name>Album Test 6</name> <created>1229460455</created> <modified>1229460475</modified> <description>this is a test album for work (xxx integration)</description> <location /> <link>http://www.xxx.com/album.php?aid=4597&id=1124262814</link> <size>1</size> <visible>everyone</visible> </album> <album> <aid>703199043023935537</aid> <cover_pid>703199231086996795</cover_pid> <owner>1124262814</owner> <name>Album Test 7</name> <created>1229459168</created> <modified>1229459185</modified> <description>Testing</description> <location /> <link>http://www.xxx.com/album.php?aid=4593&id=1124262814</link> <size>1</size> <visible>friends</visible> </album> </photos_GetAlbums_response>
Answers
-
User837036733 posted
Martin, in regards to your statement that you can just pass in a stream, what type?
I got it working but only with an XmlNodeReader. When I pass in a Stream or StreamReader, I continually get:
«There is an error in XML document (0, 0).»
{«Root element is missing.»}
and it’s the same HttpWebResponse. Look at my code above in how I’m convering the response and the different types I tried in my General class. Why wouldn’t my code work for Stream or StreamReader but would for XmlDoc? I ended up finding
out that the main probelm was I had typeOf wrong in my deserialization method.But I still want to figure out how I can get this working with a lighter solution like you said, just send the stream.
Here’s how it works with my XmlDoc but ultimately using the XmlNodeReader to get this to work without error:
public static List<Album> CreateAlbumFromXMLDoc(XmlDocument doc) { // Create an instance of a serializer var serializer = new XmlSerializer(typeof(GetAlbumsResponse)); string xmlString = doc.OuterXml.ToString(); XmlNodeReader reader = new XmlNodeReader(doc); using (reader) { GetAlbumsResponse album = (GetAlbumsResponse)serializer.Deserialize(reader); return album.Albums; } }
Now how can I get this to work with a direct stream? Look at my General Stream overload and then how can I get it working in here? Here’s what I tried but got that error mentioned above:
public static List<Album> CreateAlbumFromXMLDoc(StreamReader streamReader) { // Create an instance of a serializer var serializer = new XmlSerializer(typeof(GetAlbumsResponse)); GetAlbumsResponse album = (GetAlbumsResponse)serializer.Deserialize(streamReader); return album.Albums; } public static List<album> CreateAlbumFromXMLDoc(Stream stream) { // Create an instance of a serializer var serializer = new XmlSerializer(typeof(GetAlbumsResponse)); GetAlbumsResponse album = (GetAlbumsResponse)serializer.Deserialize(stream); return album.Albums; }</album>
-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
-
User1835330922 posted
Make sure you close the Stream and dispose of it by wrapping it into a using statement.
-
Marked as answer by
Anonymous
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
-
User1835330922 posted
Martin, in regards to your statement that you can just pass in a stream, what type?
I got it working but only with an XmlNodeReader. When I pass in a Stream or StreamReader, I continually get:
«There is an error in XML document (0, 0).»
{«Root element is missing.»}
and it’s the same HttpWebResponse.
Also note that you can’t consume the same response stream twice so if it is really the
same HttpWebResponse then the error message is correct, the stream has been consumed to the end already and further attempts to read from it will not find anything, not even a root element.-
Marked as answer by
Anonymous
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
This morning I am unable to open up a blank or any of my existing .PBIX files. I get an error stating «There is an error in XML document (1, 1). I’ve been reading posts and have uninstalled and re-installed my Power BI desktop and Personal Gateway. I’ve also deleted the AppData file users have mentioned but nothing seems to work. Below is a copy of the code I copied from the error. I’m not sure why all of a sudden this is having issues as my Power BI Desktop was working fine last friday. Also, I had another member open up a file and test and they had no issues so it seems to be on my PC. Does anyone know how to fix?
- Remove From My Forums
-
Вопрос
-
Hello All,
I’m getting the following error «There is an error in XML document (2, 2).» in a suspended instance of an orchestration invoked by a web service call. I validated the instance that is present in the suspended orchestration. Here is the
message instance in my web service call and here is a message instance generated by visual studio. The only difference I see are the namespaces but I didn’t think that should matter. I’m using XMLSerializer to load the XMLDocument type and set
it to my message in my orchestration.Instance from suspdended orchestration that validates sucessfully:
<?xml version=»1.0″
?>—
<BillImageServiceOutput xmlns:xsi=»http://www.w3.org/2001/XMLSchema-instance«
xmlns:xsd=»http://www.w3.org/2001/XMLSchema« xmlns=»http://BillImageStorageRetrieval.BillImageArchiveServiceOutput«>—
<ResultRecord xmlns=»«><ArchiveRecordId>0</ArchiveRecordId>
</ResultRecord>
</BillImageServiceOutput>
Instance generated from VS:
<ns0:BillImageServiceOutput xmlns:ns0=»http://BillImageStorageRetrieval.BillImageArchiveServiceOutput«>
—
<ResultRecord><ArchiveRecordId>0</ArchiveRecordId>
</ResultRecord>
</ns0:BillImageServiceOutput>
Thanks for the help!
Ответы
-
Thanks everyone for the responses. I have figured it out. For some reason the service reference proxy class generated by Visual Studio said that it expected a different element name other than BillImageServiceOutput.
I must have switched message types but never redeployed the web services that talked to the orchestration. I hate it when that kind of stuff happens!-
Помечено в качестве ответа
10 января 2012 г. 19:56
-
Помечено в качестве ответа
eluzor 0 / 0 / 1 Регистрация: 05.09.2015 Сообщений: 212 |
||||
1 |
||||
15.05.2016, 09:32. Показов 6952. Ответов 7 Метки нет (Все метки)
когда пытюсь десериализовать файл , то выдаёт ошибку —
0 |
161 / 122 / 85 Регистрация: 16.10.2013 Сообщений: 1,738 |
|
15.05.2016, 09:46 |
2 |
eluzor, а где кот объекта который подлежит десериализации и каким образом производится десериализация?
0 |
eluzor 0 / 0 / 1 Регистрация: 05.09.2015 Сообщений: 212 |
||||||||||||||||
15.05.2016, 10:14 [ТС] |
3 |
|||||||||||||||
открываю файл при нажатии на кнопке
Добавлено через 39 секунд
Добавлено через 57 секунд
Добавлено через 3 минуты
0 |
8927 / 4839 / 1885 Регистрация: 11.02.2013 Сообщений: 10,246 |
|
15.05.2016, 13:26 |
4 |
Скорее всего проблема в свойстве Isikukood. Оно объявлено как int, но в записи гораздо больше. Объяви его как string
1 |
eluzor 0 / 0 / 1 Регистрация: 05.09.2015 Сообщений: 212 |
||||||||||||||||||||
22.05.2016, 08:44 [ТС] |
5 |
|||||||||||||||||||
доброго времени суток! XML
STUDENT
class XmlFileSerializer
пытаюсь вывести всё в listview
нажатие на кнопке для отображения содержимого
Добавлено через 22 часа 46 минут
0 |
ViterAlex 8927 / 4839 / 1885 Регистрация: 11.02.2013 Сообщений: 10,246 |
||||
22.05.2016, 09:52 |
6 |
|||
Укажи пространства имён в xml как в первом соообщении было.
Хотя, возможно, нужно ещё задавать имя корневого элемента
0 |
0 / 0 / 1 Регистрация: 05.09.2015 Сообщений: 212 |
|
22.05.2016, 10:22 [ТС] |
7 |
поменял , но всё равно выдаёт ту же ошибку.
0 |
ViterAlex 8927 / 4839 / 1885 Регистрация: 11.02.2013 Сообщений: 10,246 |
||||
22.05.2016, 10:47 |
8 |
|||
Сообщение было отмечено eluzor как решение РешениеТогда точно, нужно указывать корневой элемент:
0 |