Pranav
Pranav

Reputation: 8871

adding Lines to Xml file At Specific location

I have an xml file "message.xml" in which messages are written like :-

< messages>
< message id="1" name="last" text="welcome All"/>
-..

-..

-..

< message id="10" name="first" text="welcome"/>
< /message>

Now i have to add message lines after last message each time through my program,
the problem is how to find the last line or place where i have to add the lines (like just before< /message> tag) ??

Upvotes: 1

Views: 1652

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could use a XDocument to manipulate XML files:

XDocument
    .Load("test.xml")
    .Root
    .Add(
        new XElement(
            "message", 
            new XAttribute("id", "123"),
            new XAttribute("name", "foo"),
            new XAttribute("text", "bar")
        )
    )
    .Save("test.xml");

Upvotes: 2

fejesjoco
fejesjoco

Reputation: 11903

Load the file into an XmlDocument (or an XDocumnent). Then you can add new message elements to the root messages element. Then resave it. No need to do text-file editing.

Upvotes: 0

Related Questions