Pergunta

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)

Foi útil?

Solução

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);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top