how can i add source node as child node in project?

this is xml file that i created using LINQ.

<?xml version="1.0" encoding="utf-16"?>
    <projects>
      <project id="2">
        <source id="2">
          <category>2</category>
        </source>
        <name>2</name>
        <category>2</category>
      </project>
    </projects>

i have used this following code.

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click

        Dim doc As XDocument = XDocument.Load("\\Demo.xml")
        Dim oDept = doc.Descendants().Elements("project").FirstOrDefault()

        Dim oEmp As New XElement("project")
        oEmp.Add(New XAttribute("id", 3))

        Dim src As New XElement("source")
        src.Add(New XAttribute("id", 3))
        src.Add(New XElement("category", 3))

        oEmp.Add(New XElement("name", 3))
        oEmp.Add(New XElement("category", 3))

        oEmp.Element("source").Add(src)
        doc.Save("\Demo.xml")
        MessageBox.Show("Added Succefully!")
 End Sub

i want to add src in oEmp using this code. Example : oEmp.Element("source").Add(src)

Answers


The way to add XElement as child of another XElement is simply call .Add() in the parent element passing child element as parameter. You already done that with <name> and <category> element here :

oEmp.Add(New XElement("name", 3))
oEmp.Add(New XElement("category", 3))

So it should be the same for <source> element :

Dim src As New XElement("source")
src.Add(New XAttribute("id", 3))
src.Add(New XElement("category", 3))
oEmp.Add(src)

Another thing, your code doesn't use oEmp element created in the end. If I understand what you're after correctly, you should add it as child of the root element (<projects>) this way before saving doc :

Dim root = doc.Root;
root.Add(oEmp);

Need Your Help

why does this Sqoop command to list tables in an Oracle database not work?

hadoop sqoop

I tried to list out the tables in a Oracle Database by using following Sqoop command:

UITapgesturerecognizer on uiimageview inside of uiscrollview

ios iphone objective-c uiscrollview uiimageview

I have an issue where the tap gesture recognizer that I've made only workes on the very last item in the scroll view.