Vishwamohan

Welcome to Vishwa's blog - Technology, Spirituality and More...

XDocument Tips

XDocument was introduced with LINQ to manipulate and query XML Document with ease. Here are some useful tips.

1. Create a simple XDocument

Dim myDoc As XDocument = <?xml version="1.0" encoding="utf-8"?><MyDocument></MyDocument>

2. Merge multiple XDcouments in one with variables and formats

Dim xDocFooter As XDocument = Nothing
Dim docName As String = "XDocument"
Dim docDate As Date = Now
 
       xDocHeader = <?xml version="1.0" encoding="utf-8"?>
                    <DocumentHeader>
                        <DocID>1</DocID>
                        <DocName><%= docName %></DocName>
                        <DocDesc>Test Document 1</DocDesc>
                        <DocDate><%= If(docDate > Date.MinValue, Format(docDate, "yyyy-MM-dd"), "1900-01-01") %></DocDate>
                    </DocumentHeader>
 
       xDocFooter = <?xml version="1.0" encoding="utf-8"?>
                    <DocumentFooter>
                        <FooterName>Footer 1</FooterName>
                        <FooterDesc>End Of Document</FooterDesc>
                    </DocumentFooter>
       myDoc.Root.Add(xDocHeader.Elements)
       myDoc.Root.Add(xDocFooter.Elements)

3. Load XML file as XDocument

Dim xdoc As XDocument = Nothing
xdoc = XDocument.Load("C:\TestXML.xml", LoadOptions.PreserveWhitespace)

4. Read XDocument from/to XML String

Dim xmlString As String = "<MyDocument>Test Doc</MyDocument>"
xdoc = XDocument.Parse(xmlString, LoadOptions.PreserveWhitespace) 'Loading from XML String
xmlString = xdoc.ToString() 'To XML String

5. Read XDocument Elements values

If myDoc.Root.Element("DocumentHeader") IsNot Nothing AndAlso myDoc.Root.Element("DocumentHeader").Element("DocName") IsNot Nothing Then
   docName = myDoc.Root.Element("DocumentHeader").Element("DocName").Value
End If
 
If myDoc.Root.Element("DocumentHeader") IsNot Nothing AndAlso myDoc.Root.Element("DocumentHeader").Element("DocDate") IsNot Nothing Then
   docDate = myDoc.Root.Element("DocumentHeader").Element("DocDate").Value
End If

6. Add New Or Modify Existing XDocument Element’s value

myDoc.Root.Element("DocumentHeader").Add(New XElement("PageNo", "1"))
myDoc.Root.Element("DocumentHeader").Element("DocDesc").Value = "New Test Document Description"
Loading