There is an error in xml document ошибка

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 Bad's user avatar

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

user875318's user avatar

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.

Amadeus Sanchez's user avatar

answered Jan 12, 2015 at 17:40

user853710's user avatar

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 Gravell's user avatar

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

j4jada's user avatar

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's user avatar

tripleee

174k33 gold badges271 silver badges313 bronze badges

answered Aug 4, 2020 at 4:57

4ever13's user avatar

In my case, a property with [XmlArrayAttribute] had the getter accessing a field with [XmlIgnoreAttribute] that was left uninitialized.

Ryan M - Regenerate response's user avatar

answered Jan 30, 2020 at 13:32

Darius's user avatar

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

code swimmer's user avatar

  • 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

  • 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

  • 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

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?

Feedback Type: Frown (Error)   Error Message: There is an error in XML document (1, 1).   Stack Trace:    at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)    at Microsoft.Mashup.Storage.Xml`1.DeserializeBytes(Byte[] bytes)    at Microsoft.Mashup.Host.Document.Storage.Local.LocalCredentialsStorage.CredentialsStorageContext.TryGetPart(CredentialsList& part)    at Microsoft.Mashup.Host.Document.Storage.Local.LocalStorageContext`1.Init()    at Microsoft.Mashup.Host.Document.Storage.Local.LocalCredentialsStorage.GetCredentials()    at Microsoft.Mashup.Host.Document.Storage.TracingCredentialsStorage.GetCredentials()    at Microsoft.PowerBI.Client.Windows.AnalysisServices.PersistedModelSanitizer.CreateCredentialManager()    at Microsoft.PowerBI.Client.Windows.AnalysisServices.PersistedModelSanitizer.TryRestoreModel(IDataModel dataModel, ModelChange& modelChange)    at Microsoft.PowerBI.Client.Windows.AnalysisServices.AnalysisServicesDatabaseLocal.BuildActionToRestoreConnectionStringCredentials(Action& restoreCredentialsAction)    at Microsoft.PowerBI.Client.Windows.ReportPreparer.ApplyStoredDirectQueryCredentials(Report report, IPowerBIWindowService windowService)    at Microsoft.PowerBI.Client.Windows.Services.PowerBIPackagingService.Open(FileStream fileStream, IPowerBIWindowService windowService, Nullable`1 entryPoint, PowerBIPackageOpenOptions options, Boolean& allCredentialsSatisfied)    at Microsoft.PowerBI.Client.Windows.Services.FileManager.<LoadFromPbix>d__5.MoveNext() — End of stack trace from previous location where exception was thrown —    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at Microsoft.PowerBI.Client.Windows.Services.UIBlockingService.<>c__DisplayClassa`1.<<BlockUIAndRun>b__9>d__c.MoveNext() — End of stack trace from previous location where exception was thrown —    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at Microsoft.PowerBI.Client.Windows.Services.UIBlockingService.WaitOnUIThreadForTaskCompletion(Task task)    at Microsoft.PowerBI.Client.Windows.Services.UIBlockingService.BlockUIAndRun[T](Func`1 asyncMethod)    at Microsoft.PowerBI.Client.Windows.Services.FileManager.OpenFile(IPowerBIWindowService windowService, IPbixFile fileToOpen, Nullable`1 entryPoint)    at Microsoft.PowerBI.Client.Program.TryOpenOrCreateReport(IUIHost uiHost, ISplashScreen splashScreen, IFileManager fileManager, IFileHistoryManager fileHistoryManager, String filePath, FileType fileType)    at Microsoft.PowerBI.Client.Program.<>c__DisplayClass10.<Main>b__0()    at Microsoft.PowerBI.Client.Windows.IExceptionHandlerExtensions.<>c__DisplayClass7.<HandleExceptionsWithNestedTasks>b__6()    at Microsoft.Mashup.Host.Document.ExceptionHandlerExtensions.HandleExceptions(IExceptionHandler exceptionHandler, Action action)   Stack Trace Message: There is an error in XML document (1, 1).   Invocation Stack Trace:    at Microsoft.Mashup.Host.Document.ExceptionExtensions.GetCurrentInvocationStackTrace()    at Microsoft.Mashup.Client.UI.Shared.StackTraceInfo..ctor(String exceptionStackTrace, String invocationStackTrace, String exceptionMessage)    at Microsoft.PowerBI.Client.Windows.Telemetry.PowerBIUserFeedbackServices.GetStackTraceInfo(Exception e)    at Microsoft.PowerBI.Client.Windows.Telemetry.PowerBIUserFeedbackServices.ReportException(IWindowHandle activeWindow, IUIHost uiHost, FeedbackPackageInfo feedbackPackageInfo, Exception e, Boolean useGDICapture)    at Microsoft.Mashup.Client.UI.Shared.UnexpectedExceptionHandler.<>c__DisplayClass1.<HandleException>b__0()    at Microsoft.Mashup.Client.UI.Shared.UnexpectedExceptionHandler.HandleException(Exception e)    at Microsoft.Mashup.Host.Document.ExceptionHandlerExtensions.HandleExceptions(IExceptionHandler exceptionHandler, Action action)    at Microsoft.PowerBI.Client.Program.Main(String[] args)     InnerException.Stack Trace Message: Data at the root level is invalid. Line 1, position 1.   InnerException.Stack Trace:    at System.Xml.XmlTextReaderImpl.Throw(Exception e)    at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()    at System.Xml.XmlTextReaderImpl.ParseDocumentContent()    at System.Xml.XmlReader.MoveToContent()    at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderCredentialsList.Read6_CredentialsList()   InnerException.Invocation Stack Trace:    at Microsoft.Mashup.Host.Document.ExceptionExtensions.GetCurrentInvocationStackTrace()    at Microsoft.Mashup.Client.UI.Shared.FeedbackErrorInfo.GetFeedbackValuesFromException(Exception e, String prefix)    at Microsoft.Mashup.Client.UI.Shared.FeedbackErrorInfo.CreateAdditionalErrorInfo(Exception e)    at Microsoft.Mashup.Client.UI.Shared.FeedbackErrorInfo..ctor(String message, Exception exception, Nullable`1 stackTraceInfo, String messageDetail)    at Microsoft.PowerBI.Client.Windows.Telemetry.PowerBIUserFeedbackServices.ReportException(IWindowHandle activeWindow, IUIHost uiHost, FeedbackPackageInfo feedbackPackageInfo, Exception e, Boolean useGDICapture)    at Microsoft.Mashup.Client.UI.Shared.UnexpectedExceptionHandler.<>c__DisplayClass1.<HandleException>b__0()    at Microsoft.Mashup.Client.UI.Shared.UnexpectedExceptionHandler.HandleException(Exception e)    at Microsoft.Mashup.Host.Document.ExceptionHandlerExtensions.HandleExceptions(IExceptionHandler exceptionHandler, Action action)    at Microsoft.PowerBI.Client.Program.Main(String[] args)
  • 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:xsihttp://www.w3.org/2001/XMLSchema-instance«
    xmlns:xsd
    http://www.w3.org/2001/XMLSchema« xmlnshttp://BillImageStorageRetrieval.BillImageArchiveServiceOutput«>


    <ResultRecord xmlns«>

    <ArchiveRecordId>0</ArchiveRecordId>

    </ResultRecord>

    </BillImageServiceOutput>

    Instance generated from VS:

    <ns0:BillImageServiceOutput xmlns:ns0http://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

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

когда пытюсь десериализовать файл , то выдаёт ошибку —
There is an error in XML document (8,5)
Подскажите, в чем может быть проблема.

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?xml version="1.0" encoding="windows-1251"?>
<ArrayOfStudent xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Student>
    <Name>Nikolai</Name>
    <Surname>Morozov</Surname>
    <Groupnumber>121</Groupnumber>
    <Isikukood>39494323943</Isikukood>          
  </Student>
  <Student>
    <Name>Maksim</Name>
    <Surname>Antonov</Surname>
    <Groupnumber>122</Groupnumber>
    <Isikukood>390943234943</Isikukood>         
  </Student>
  <Student>
    <Name>Anastasia</Name>
    <Surname>Erofeeva</Surname>
    <Groupnumber>123</Groupnumber>
    <Isikukood>386943234944</Isikukood>         
  </Student>
  <Student>
    <Name>Aleksandr</Name>
    <Surname>Alekseev</Surname>
    <Groupnumber>124</Groupnumber>
    <Isikukood>380943234943</Isikukood>         
  </Student>
  <Student>
    <Name>Dmitri</Name>
    <Surname>Mihailov</Surname>
    <Groupnumber>125</Groupnumber>
    <Isikukood>3809437634973</Isikukood>            
  </Student>
  <Student>
    <Name>Stepan</Name>
    <Surname>Manzurets</Surname>
    <Groupnumber>222</Groupnumber>
    <Isikukood>3899437634973</Isikukood>            
  </Student>
</ArrayOfStudent>



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

открываю файл при нажатии на кнопке

C#
1
2
3
4
5
6
        private void FileContent_Click(object sender, EventArgs e)
        {
            spisok = XmlFileSerializer.Open(@"C:UsersadminDocumentsVisual Studio 2013ProjectsStudentGroupStudentGroupbinDebugIATI.xml");
 
            PopulateStudentListView();
        }

Добавлено через 39 секунд
метод PopulateStudentListView();

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void PopulateStudentListView()
        {
            foreach (Student obj in spisok)         // idem po kazdomu objektu Students
            {
                ListViewItem lvi = new ListViewItem();
 
                foreach (PropertyInfo pi in obj.GetType().GetProperties())      // dostaju po poljam etogo klassa
                {
                    string str;
 
                    if (pi.Name == "Name")
                    {
                        str = pi.GetValue(obj).ToString();
                        lvi.Text = str;
                    }
                    else
                    {
                        str = pi.GetValue(obj).ToString();
                        lvi.SubItems.Add(str);
                    }
                }
                lvStudent.Items.Add(lvi);
            }
        }

Добавлено через 57 секунд
вот сам объект

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace StudentGroup
{
    [Serializable]
    public  class Student
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Groupnumber { get; set; }
        public int Isikukood { get; set; }
 
 
 
 
        public Student()
        {
 
        }
 
           public Student(string name, string surname, int groupnumber, int  isikukood)
            {
               this.Name = name;
               this.Surname = surname;
               this.Groupnumber = groupnumber;
               this.Isikukood = isikukood;
            }
 
 
        public override string ToString()
        {
            return string.Format("{0}n{1}n{2}n{3}",Name,Surname,Groupnumber,Isikukood);
        }
    }
}

Добавлено через 3 минуты
XmlFileSerializer сделан как отдельный класс

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Windows.Forms;
 
using System.IO;
using System.Xml.Serialization;
 
namespace StudentGroup
{
    class XmlFileSerializer
    {
        static XmlSerializer xmls =
           new XmlSerializer(typeof(List<Student>));
 
 
        public static List<Student> Open(string fileName)
        {
            if (string.IsNullOrEmpty(fileName.Trim())) return null;
 
            List<Student> list = new List<Student>();
            try
            {
                StreamReader sr = new StreamReader(fileName, Encoding.Default);
 
                list = (List<Student>)xmls.Deserialize(sr);
 
                sr.Close();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
            return list;
        }
    }
}



0



8927 / 4839 / 1885

Регистрация: 11.02.2013

Сообщений: 10,246

15.05.2016, 13:26

4

Скорее всего проблема в свойстве Isikukood. Оно объявлено как int, но в записи гораздо больше. Объяви его как string
А вообще смотри InnerException у ошибки, спускаясь вниз по дереву ошибок, чтобы понять где ошибка возникла впервые



1



eluzor

0 / 0 / 1

Регистрация: 05.09.2015

Сообщений: 212

22.05.2016, 08:44

 [ТС]

5

доброго времени суток!
сного у меня возникла ошибка во время считывания XML файла. На этот раз There is an error in XML document (2,2).
Необходима ваша помощь друзья!

XML

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<Students>
  <Student>
    <Name>Dmitrii</Name>
    <Surname>Malcev</Surname>
    <Groupnumber>121</Groupnumber>
    <Isikukood>77777777777</Isikukood>
  </Student>
  <Student>
    <Name>Anton</Name>
    <Surname>Gurov</Surname>
    <Groupnumber>121</Groupnumber>
    <Isikukood>11111111111</Isikukood>
  </Student>
</Students>

STUDENT

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Xml.Serialization;
 
namespace StudentGroup
{
    public  class Student
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public string Groupnumber { get; set; }
        public string Isikukood { get; set; }
 
 
 
 
        public Student()
        {
 
        }
 
        public Student(string name, string surname, string groupnumber, string isikukood)
            {
               this.Name = name;
               this.Surname = surname;
               this.Groupnumber = groupnumber;
               this.Isikukood = isikukood;
            }
 
 
        //public override string ToString()
        //{
        //    return string.Format("{0}n{1}n{2}n{3}",Name,Surname,Groupnumber,Isikukood);
        //}
    }
}

class XmlFileSerializer

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Windows.Forms;
 
using System.IO;
using System.Xml.Serialization;
 
namespace StudentGroup
{
    class XmlFileSerializer
    {
        static XmlSerializer xmls =
           new XmlSerializer(typeof(List<Student>));
 
 
        public static List<Student> Open(string fileName)
        {
            if (string.IsNullOrEmpty(fileName.Trim())) return null;
 
            List<Student> list = new List<Student>();
            try
            {
                StreamReader sr = new StreamReader(fileName, Encoding.Default);
 
                list = (List<Student>)xmls.Deserialize(sr);
 
                sr.Close();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
            return list;
        }
    }
}

пытаюсь вывести всё в listview

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 void PopulateStudentListView()
        {
                foreach (Student obj in spisok)         // idem po kazdomu objektu Students
                {
                    ListViewItem lvi = new ListViewItem();
 
                    foreach (PropertyInfo pi in obj.GetType().GetProperties())    
                    {
                        string str;
 
                        if (pi.Name == "Name")
                        {
                            str = pi.GetValue(obj).ToString();
                            lvi.Text = str;
                        }
                        else
                        {
                            str = pi.GetValue(obj).ToString();
                            lvi.SubItems.Add(str);
                        }
                    }
                    lvStudent.Items.Add(lvi);
                }
            }

нажатие на кнопке для отображения содержимого

C#
1
2
3
4
5
6
        private void FileContent_Click(object sender, EventArgs e)
        {
            spisok = XmlFileSerializer.Open("IATI.XML");
 
            PopulateStudentListView();
        }

Добавлено через 22 часа 46 минут
никто не видит ошибок ?



0



ViterAlex

8927 / 4839 / 1885

Регистрация: 11.02.2013

Сообщений: 10,246

22.05.2016, 09:52

6

Укажи пространства имён в xml как в первом соообщении было.

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<Students  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Student>
    <Name>Dmitrii</Name>
    <Surname>Malcev</Surname>
    <Groupnumber>121</Groupnumber>
    <Isikukood>77777777777</Isikukood>
  </Student>
  <Student>
    <Name>Anton</Name>
    <Surname>Gurov</Surname>
    <Groupnumber>121</Groupnumber>
    <Isikukood>11111111111</Isikukood>
  </Student>
</Students>

Хотя, возможно, нужно ещё задавать имя корневого элемента



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 как решение

Решение

Тогда точно, нужно указывать корневой элемент:

C#
1
2
3
4
5
6
using (var reader = new StreamReader("students.xml"))
{
    var root = new XmlRootAttribute("Students");//Говорим, что корневой элемент называется Students
    var serializer = new XmlSerializer(typeof(List<Student>), root);//Указываем корневой элемент сериализатору
    List<Student> students = (List<Student>)serializer.Deserialize(reader);
}



0



Понравилась статья? Поделить с друзьями:
  • Thermo king v100 max ошибка
  • There from san francisco ошибка
  • There are some water in the glass исправить ошибки
  • Thermo king slx 200 коды ошибок
  • There are elephants in my garden исправить ошибку