VB.NET - 编辑XML并删除行(如果存在)

时间:2016-04-16 03:59:12

标签: xml vb.net edit

我遇到这种情况:

1- load xml

2-搜索是否存在行(或单词)

3-如果存在则删除整行

4-保存

加载并保存xml ok,但是2和3 dunno ......

XML

<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" IgnorableNamespaces="uap mp build" xmlns:build="http://schemas.microsoft.com/developer/appx/2015/build">
  <Identity Name="Microsoft.MyApp" Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" Version="1.5.0.0" ProcessorArchitecture="x64" />
  <mp:appid Id1="1111" Id2="3333" />
</Package>

因此,如果存在mp:appid,则删除整行

结果应该是:

<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" IgnorableNamespaces="uap mp build" xmlns:build="http://schemas.microsoft.com/developer/appx/2015/build">
  <Identity Name="Microsoft.MyApp" Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" Version="1.5.0.0" ProcessorArchitecture="x64" />
</Package>

我想我必须使用XML命名空间......

所有人,为我的坏人而努力...

1 个答案:

答案 0 :(得分:0)

试试xml linq

Imports System.Xml
Imports System.Xml.Linq
Module Module1
    Const FILENAME As String = "c:\temp\test.xml"
    Sub Main()
        Dim doc As XDocument = XDocument.Load(FILENAME)

        Dim appid As XElement = doc.Descendants().Where(Function(x) CType(x.Name.LocalName, String) = "appid").FirstOrDefault()
        If Not appid Is Nothing Then
            appid.ReplaceWith(Nothing)
        End If
        doc.Save(FILENAME)
    End Sub

End Module