简体   繁体   中英

How can i read from xml file only the text line by line with date and time parse from the xml file?

In this code im using InnerText to view only the text from the xml file without any tags. But i want two things to change now:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string xmlString = @"d:\adilipman1937067724.xml";

            XmlDocument doc = new XmlDocument();
            doc.Load(xmlString);
            string t = doc.InnerText;
            textBox1.Text = t;
        }
    }
}
  1. To parse the text to lines.

  2. To parse and add to each line the date and time.

Here is an example of the xml file i want to parse from:

FriendlyName="adilipman@yahoo.com"/></To><Text Style="font-family:Segoe UI; color:#000000; ">testing the test.</Text></Message><Message Date="31/01/2012" Time="10:15:58" DateTime="2012-01-31T08:15:58.897Z" SessionID="1"><From><User FriendlyName="Chocolade"/></From><To><User 

Instead to put in a string only the text "testing the test" i want it to be format in the textBox1 like:

adilipman 10:15:58 31/01/2012 testing the test      

This is a line. Next line will be for example:

adilipman 10:15:59 31/01/2012 testing the test was ok 

But now what im getting in the textBox1 is like this:

testing the test testing the test was ok 

Some more text from the xml file:

<?xml version="1.0"?>
<?xml-stylesheet type='text/xsl' href='MessageLog.xsl'?>
<Log FirstSessionID="1" LastSessionID="2"><Message Date="31/01/2012" Time="10:15:42" DateTime="2012-01-31T08:15:42.467Z" SessionID="1"><From><User FriendlyName="Chocolade"/></From><To><User FriendlyName="adilipman@yahoo.com"/></To><Text Style="font-family:Segoe UI; color:#000000; ">היי</Text></Message><Message Date="31/01/2012" Time="10:15:55" DateTime="2012-01-31T08:15:55.097Z" SessionID="1"><From><User FriendlyName="Chocolade"/></From><To><User FriendlyName="adilipman@yahoo.com"/></To><Text Style="font-family:Segoe UI; color:#000000; ">הייתה לי בעיה עם התוכנת ברקים אבל עכשיו הכל עובד.</Text></Message><Message Date="31/01/2012" Time="10:15:58" DateTime="2012-01-31T08:15:58.897Z" SessionID="1"><From><User FriendlyName="Chocolade"/></From><To><User FriendlyName="adilipman@yahoo.com"/></To><Text Style="font-family:Segoe UI; color:#000000; ">מה השלב הבא ?</Text></Message><Message Date="31/01/2012" Time="10:16:27" DateTime="2012-01-31T08:16:27.775Z" SessionID="1"><From><User FriendlyName="Chocolade"/></From><To><User FriendlyName="adilipman@yahoo.com"/></To><Text Style="font-family:Segoe UI; color:#000000; ">אמרת לי בזמנו לחשב ממוצע של 1000 ערכים ? הכוונה 1000 ערכים בפריים ? כי בפריים יש 256 מספרים לא ?</Text></Message><Message Date="31/01/2012" Time="10:17:03" DateTime="2012-01-31T08:17:03.405Z" SessionID="1"><From><User FriendlyName="adilipman@yahoo.com"/></From><To><User FriendlyName="Chocolade"/></To><Text Style="font-family:Segoe UI; color:#000000; ">לחשב ממוצע של 1000 הערכים הגבוהים ביותר בהיסטוגרמה</Text></Message><Message Date="31/01/2012" Time="10:17:10" DateTime="2012-01-31T08:17:10.405Z" SessionID="1"><From><User FriendlyName="adilipman@yahoo.com"/></From><To><User FriendlyName="Chocolade"/></To><Text Style="font-family:Segoe UI; color:#000000; ">ז"א בפריים</Text></Message><Message Date="31/01/2012" Time="10:17:14" DateTime="2012-01-31T08:17:14.135Z" SessionID="1"><From><User FriendlyName="adilipman@yahoo.com"/></From><To><User FriendlyName="Chocolade"/></To><Text Style="font-family:Segoe UI; color:#000000; ">לא בהיסטוגרמה</Text></Message><Message Date="31/01/2012" Time="10:17:20" DateTime="2012-01-31T08:17:20.142Z" SessionID="1"><From><User 

There are a lot of different ways to parse xml document... Using XmlDocument , XmlTextReader s but i prefer to use Linq to xml classes for parsing existing xml documents, but if I have to create my oun xml document and then parse it I prefer to use Serialization. I'm saing than becouse I don't know where did you take that xml document??? Did you crate it yourself??? If yes you should use xml serialization to save your own objects to xml and deserialization to read them back. It is much easier than parse xml document.

Here is an easiest example similar to yours question: As I can understand from your xml example... I used this xml fragment:

<Message Date="31/01/2012" 
         Time="10:15:58" 
         DateTime="2012-01-31T08:15:58.897Z" 
         SessionID="1">
         <From>
               <User FriendlyName="Chocolade"/>
         </From>
         <To>
               <User FriendlyName="adilipman@yahoo.com"/>
         </To>
         <Text >testing the test.</Text>
</Message>

You should create Message class with DateTime, SessionId,From,To and Text fields. Something like:

[Serializable]
public class User
{
      public string FriendlyName { get; set; }
}

[Serializable]
public class Message
{
      public string Text { get; set; }
      public DateTime DateTime { get; set; }
      public int SessionID { get; set; }
      public User Form { get; set; }
      public User To { get; set; }
}

[Serializable] attribute is necessary for compiler to know that your type (Message) can be serialized. And after creating you class xml structure you can serialize any instance of your Message or eve array of them List<Message> . You should do next:

private void button1_Click(object sender, EventArgs e)
{
string xmlToSerializePath = @"c:/temp/stackowrflowquestionxml.xml";

XmlSerializer serializer = new XmlSerializer(typeof(Message));
StreamWriter writer = new StreamWriter(xmlToSerializePath);

Message messageToSerialize = new Message
                                    {
                                        DateTime = new DateTime(2012, 1, 31, 8, 15, 58),
                                        Form = new User()
                                                  {
                                                        FriendlyName = "Chocolade"
                                                  },
                                        To = new User
                                                  {
                                                        FriendlyName = "adilipman@yahoo.com"
                                                  },
                                        SessionID = 1,
                                        Text = "testing the test."
                                     };
       serializer.Serialize(writer, messageToSerialize);
       writer.Close();
}

You will get the next xml document:

<?xml version="1.0" encoding="utf-8"?>
<Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>testing the test.</Text>
  <DateTime>2012-01-31T08:15:58</DateTime>
  <SessionID>1</SessionID>
  <Form>
    <FriendlyName>Chocolade</FriendlyName>
  </Form>
  <To>
    <FriendlyName>adilipman@yahoo.com</FriendlyName>
  </To>
</Message>

It is quite similar to yours but now if you need to get all information about that message you don't need to pase xml, you just need to deserialize it and get correct instance of your own Message class:

StreamReader reader = new StreamReader(xmlToSerializePath);
Message deserializedMessage = (Message)serializer.Deserialize(reader);
reader.Close();

When you get your instance of message you can manipulate it like you want and fill that textbox with any information of your message:

textBox1.Text = string.Format("{0} {1} {2} {3}", 
          deserializedMessage.DateTime, 
          deserializedMessage.Form.FriendlyName, 
          deserializedMessage.To.FriendlyName, 
          deserializedMessage.SessionID);

Textbox text will be the following:

31.01.2012 8:15:58 Chocolade adilipman@yahoo.com 1

/ ================================================================================== /

if you dont like or dont want to use such methodology, or you just need to parse already created by some third person xml, you can use linq to xml syntax. For example:

Create XDocument instance:

string xmlStringPath = @"d:/adilipman1937067724.xml";
XDocument document = new XDocument(xmlStringPath);

but sometimes it can throw the exception, so you need to create XmlDocument, load xml as string, and use static XDocument method to parse that string:

XmlDocument doc = new XmlDocument();
doc.Load(xmlString);
XDocument document = XDocument.Parse(doc.OuterXml);

Pay attention about XDocument and XmlDocument. These are two different types. Then you can parse your document using linq syntax:

// Get root message element
var messageElement = (from element in document.Elements()
                                  where element.Name == "Message"
                                  select element).FirstOrDefault();

// Get date attribute of message element
string date = messageElement.Attribute("Date").Value;

// Get To element
// Notice that we make select from elements of message element messageElement.Elements()
// You should closely follow about what attribute are you making select from,
// because your selection will return null, and you will get errors.
var toElement = (from element in messageElement.Elements()
                             where element.Name == "To"
                                select element).FirstOrDefault();

// Then we take value of user element friendly name attribute
// We get element (tag) User of all possible existing sub tags of tag To
string toFriendlyName =
                (from element in toElement.Elements()
                 where element.Name == "User"
                 select element.Attribute("FriendlyName").Value).FirstOrDefault();

And so on for every attribute or element. As you can see it is very difficult and bulky work to parse xml "by hands". So i would recommend you to use Serialization. Hope my answer helped you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM