简体   繁体   中英

How to edit XML node using combobox (VB.Net)

I'm trying to edit the Income node, and am achieving this with the current code. However all other elements (RptMenu and Icon) are being removed. I want them to remain in the XML file and only Income to be changed to whatever the textbox sets. A combobox is used to select which MenuItem (Income, Stock etc) is to be changed.

XML Code: (There are more menu items not included to keep it simple)

<ReportMenu>

<RptMenu category="Menu">
    <MenuItem>Income</MenuItem>
    <Icon>C:\Documents\Visual Studio 2008\Projects\Menu\Menu\Resources\IncomeImage.jpg</Icon>
  </RptMenu>

<RptMenu category="Menu">
    <MenuItem>Stock</MenuItem>
    <Icon>C:\Documents\Visual Studio 2008\Projects\Menu\Menu\Resources\IncomeImage.jpg</Icon>
  </RptMenu>

 </ReportMenu>

vb.net Code:

Private Sub btnEditCategory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEditCategory.Click

Dim xd As New XmlDocument()
        xd.Load("C:\Documents\Reports.xml")

        Dim newNode As XmlElement = xd.CreateElement("MenuItem")
        newNode.InnerText = txtAddCategory.Text

        For Each oldNode As XmlNode In xd.SelectNodes("ReportMenu/RptMenu")

            If oldNode.SelectSingleNode("MenuItem").InnerText = cmbCategory.Text Then
                oldNode.ParentNode.ReplaceChild(newNode, oldNode)
            End If

        Next
        xd.Save("C:\Documents\Reports.xml")

    End Sub

Try this:

<?xml version="1.0" encoding="utf-8"?>
<Profiles>
<Name>
</Name>
</Profiles>

OR

Dim doc As XDocument = XDocument.Load("Profiles.xml")
ComboBox1.DataSource = (From element In doc.Descendants("Name") Select element.Value).ToList()

Demo:

http://social.msdn.microsoft.com/Forums/vstudio/en-US/1faf99bd-f22e-4f52-aa0a-2d4328835537/c-change-xml-node

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM