【问题标题】:Insert new data into specified node in XML file将新数据插入 XML 文件中的指定节点
【发布时间】:2019-01-11 22:51:05
【问题描述】:

我想使用 vb 代码在 <channel> 标记内插入一个新元素。我的代码在 <channel><rss> 结束标签 end 之后添加了新项目

我已经试过了:

document.Root.Elements.First().Add(root)

但是没有用。

我的 xml 文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
    <channel>

    </channel>
</rss>

这是我的代码:

FilePath = "h:\root\home\ka-001\www\site1\xmlfile1.xml"
Dim document As XDocument = New XDocument()

If File.Exists(FilePath) Then
        document = XDocument.Load(FilePath)
Else
        Label1.Text = "! file dosn't exist"
End If

If FileUpload1.HasFile = True Then
        If FileUpload1.PostedFile.ContentLength <= size Then
            Dim strPath As String
            strPath = "~/files/" & FileUpload1.FileName
            FileUpload1.SaveAs(MapPath(strPath))
        End If
    End If

    attac1 = FileUpload1.FileName

    Dim root As XElement = New XElement("item")
    Dim title As XElement = New XElement("title", New XCData(TextBox3.Text))
    Dim link As XElement = New XElement("link", TextBox6.Text)

    root.Add(title, link)
    document.Root.Add(root)
    document.Save(FilePath)
    Label1.Text = "! done"

【问题讨论】:

    标签: asp.net xml vb.net visual-studio visual-studio-2012


    【解决方案1】:

    您不想将新元素添加到 root(即 &lt;rss&gt; 元素) - 但要添加到 &lt;channel&gt; 子元素 - 所以你需要先抓住那个- 像这样(C# 中的代码 - 应该很容易转换为 VB.NET):

    var channelNode = document.Root.Descendants("channel").FirstOrDefault();
    

    然后,一旦你有了那个通道节点,你就可以向它添加新元素 - 我假设你想添加一个元素 &lt;item&gt; 和两个子元素 - 对吗?

    这可以通过以下代码完成:

    // create new <item> element
    XElement item = new XElement("item");
    
    // add sub-element <title> to <item>
    item.Add(new XElement("title", new XCData(TextBox3.Text)));
    
    // add sub-element <link> to <item>
    item.Add(new XElement("link", TextBox6.Text));
    
    // and now add the <item> element inside the <channel> element
    channelNode.Add(item);
    

    【讨论】:

      猜你喜欢
      • 2020-10-17
      • 1970-01-01
      • 2019-01-30
      • 2017-08-15
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多