0

I have an array which its structure is:

<data>
<id></id>
<list></list>
</data>

And I want to write an array to list node

<data>
<id></id>
<list>
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
</list>
</data>

Then, delete an element in that array:

<data>
<id></id>
<list>
    <item>1</item>
    <item>3</item>
    <item>4</item>
</list>
</data>

Next, modify that array:

<data>
<id></id>
<list>
    <item>1</item>
    <item>2</item>
    <item>3</item>
</list>
</data>

How to write / read/ modify an array which inside the xml array?

Any ideas?

5
  • XElement, XDocument are few examples which you can read Commented Nov 14, 2016 at 7:32
  • 2
    Possible duplicate of Editing XML document using C# Commented Nov 14, 2016 at 7:33
  • @Damith I read it as a text file. Split it by <list> first, then remove </list>. Second, get all data in <item> node by using split and convert it to list. Commented Nov 14, 2016 at 8:12
  • @cansik What I have to do with your suggested answer? var page = xdoc.Descendants("data"); if (page != null) { page.Element("list") .Add(new XElement("item", 4 )); xdoc.Save("Test.xml"); } Commented Nov 14, 2016 at 8:17
  • @MRfuxkYou It's about editing an xml file with C#. You did not ask a concrete question, so learn first to work with xml files and then ask a specific question if you have one. Commented Nov 14, 2016 at 8:23

1 Answer 1

2

To read:

XDocument doc = XDocument.Load("data.xml");
var listPath = from elements in doc.Elements("data").Elements("list") select elements;

foreach (var docItem in listPath)
{
 var itemVar= Convert.ToInt32(doc .Element("item").Value);               
}

To write:

XDocument doc = XDocument.Load("data.xml");
var list = doc.Root.Element("list");
list.Add(new XElement("item", value));

To edit:

XDocument doc = XDocument.Load("data.xml");
var list = doc.Root.Element("list");
list.Element("item").Value = newValue;

any powerful and faster solution?

Sign up to request clarification or add additional context in comments.

1 Comment

Hey, does anyone know how to delete all item in list?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.