Using XmlTextReader

后端 未结 3 1769
感情败类
感情败类 2021-01-18 10:55

I am a beginner programmer starting off with C#, and web services.

In the Service.cs file of my web service, I create a ReadXMLFile() meth

相关标签:
3条回答
  • 2021-01-18 11:16

    You're probably missing IsStartElement() condition in your while loop:

    while (reader.Read())
    {
        if (reader.IsStartElement())
        {
           if (reader.Name == "id")
           {
               id = reader.ReadString();
           }
    ...
    }
    

    Also, it would be easier to use XPath or LINQ to XML to read your XML, of course it depends on the file. Here are some examples: XPath and LINQ.

    EDIT: after seeing XML file details

    You should update your logic to keep track of current student and its testscores. Also, note that count is an attribute. It can get messy pretty soon, I suggest you take a look at the samples mentioned above.

    0 讨论(0)
  • 2021-01-18 11:28

    The reason its not working because, example: when reader.Name == "firstname" is true but its not true with its elements value. What it exactly means is reader object reads next Nodetype, which is XmlNodeType.Element. So in this case looking at your XML file, using reader.Read(); function again reads next node, which is XmlNodeType.Text, and its value is then Joe. Im givin you example of working version.

    void ReadXMLFile()
    {
    XmlTextReader reader = new XmlTextReader("ClassRoll.xml");
    reader.Read();
    while (reader.Read())
    {
        if (reader.Name == "id")
        {
             reader.Read();
             if(reader.NodeType == XmlNodeType.Text)
             {
               id = reader.Value;
               reader.Read();
             }
    
        }
     }
    

    }

    0 讨论(0)
  • 2021-01-18 11:32

    I think, that you get best result using XmlDocument

    public void ReadXML()
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("<name file>.xml");
        xmlEntities = new List<XmlEntity>();
    
        foreach(XmlNode item in xmlDoc.ChildNodes)
        {
            GetChildren(item);
        }
    }
    
    private void GetChildren(XmlNode node)
    {
        if (node.LocalName == "Строка")
        {
           //<you get the element here and work with it>
        }
        else
        {
           foreach (XmlNode item in node.ChildNodes)
           {
                 GetChildren(item);
           }
        }
    }
    
    0 讨论(0)
提交回复
热议问题