Parse XML file with XDocument
In this chapter you will learn:
- How to load XML file with XDocument
- Loading a Document with the XDocument.Load Method with LoadOptions
How to load XML file with XDocument
using System;// j a v a 2 s.c o m
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
class Program {
static void Main(string[] args) {
XmlReader reader = XmlReader.Create("Employee.xml");
XDocument xml = XDocument.Load(reader);
Console.WriteLine(xml);
XElement idperson = xml.Descendants("idP").Last();
idperson.Add(new XElement("idperson",
new XAttribute("id", 1),
new XAttribute("year", 2006),
new XAttribute("salary", "16")));
StringWriter sw = new StringWriter();
XmlWriter w = XmlWriter.Create(sw);
xml.Save(w);
w.Close();
Console.WriteLine(sw.ToString());
}
}
Loading a Document with the XDocument.Load Method with LoadOptions
using System;//from j ava2 s .c om
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
public class MainClass {
public static void Main() {
XDocument xDocument = XDocument.Load("book.xml",LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);
Console.WriteLine(xDocument);
XElement firstName = xDocument.Descendants("FirstName").First();
Console.WriteLine("FirstName Line:{0} Position:{1}",((IXmlLineInfo)firstName).LineNumber,((IXmlLineInfo)firstName).LinePosition);
Console.WriteLine("FirstName Base URI:{0}", firstName.BaseUri);
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » XML Linq