如何用C#删除xml元素? [英] How to delete xml element with C#?

查看:69
本文介绍了如何用C#删除xml元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 XML 的新手,在理解如何实现删除树中某些元素的解决方案时遇到了问题.我已经寻找了一个解决方案并尝试了很多例子,但没有产生任何让我满意的东西.希望有人能有所启发.可能真的很简单,但我很想念它,因为我刚刚开始使用 XML.

I'm new to XML and am having a problem understanding how to implement a solution of deleting certain elements within the tree. I've searched for a solution and have tried numerous examples, but have not generated anything that satisfies me. Hoping that someone may shed some light. Probably real simply, but I'm missing it since I'm just starting with XML.

示例 XML 将是:

<?xml version="1.0"?>
    <configuration>
      <configSections>
        <sectionGroup name="system.sm">
          <section name="domainServices" type="System.sm.DomainServices.Hosting.DomainServicesSection, System.sm.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineTABCplication" requirePermission="false" />
        </sectionGroup>
      </configSections>
      <appSettings>
        <add key="useRemote" value="false" />
        <add key="sandboxFolder" value="D:\Sandbox" />
        <add key="imageFilesFolder" value="Images" />
      </appSettings>
      <runtime>
        <assemblylock xmlns="urn:schemas-microsoft-com:asm.v1">
          <probing privatePath="Platform/bin;ProductBin" />
        </assemblylock>
      </runtime>
      <connectionStrings>
        <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
      </connectionStrings>
      <system.web>
        <httpModules>
          <add name="DomainServiceModule" type="System.sm.DomainServices.Hosting.DomainServiceHttpModule, System.sm.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        </httpModules>
        <compilation debug="true" targetFramework="4.0" />
        <globalization culture="auto" uiCulture="auto" />
        <authentication mode="Forms">
          <forms protection="All" />
        </authentication>
        <roleManager enabled="true">
        </roleManager>
        <profile>
          <providers>
            <clear />
            <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
          </providers>
          <properties>
            <add name="FriendlyName" />
          </properties>
        </profile>
        <httpRuntime maxRequestLength="10240" />
      </system.web>
      <system.ws>
        <validation validateIntegratedModeConfiguration="false" />
        <modules runAllManagedModulesForAllRequests="true">
          <add name="DomainServiceModule" preCondition="managedHandler" type="System.sm.DomainServices.Hosting.DomainServiceHttpModule, System.sm.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        </modules>
      </system.ws>
      <system.sm>
        <client>
          <endpoint address="net.tcp://localhost:5256/HTM" lock="netTcplock" lockConfiguration="NetTcplock_Service" contract="ProductHFSReference.Service" name="NetTcplock_Service" />
          <endpoint address="http://localhost:5255/HTM/basic" lock="basicHttplock" lockConfiguration="BasicHttplock_Service" contract="ProductHFSReference.Service" name="BasicHttplock_Service" />
          <endpoint address="http://localhost:5255/HTM/ws" lock="wsHttplock" lockConfiguration="WSHttplock_Service1" contract="ProductHFSReference.Service" name="WSHttplock_Service1" />
          <endpoint address="http://localhost:5255/DManager/ws" lock="wsHttplock" lockConfiguration="WSHttplock_IDevicePool" contract="DManagerServiceReference.IDevicePool" name="WSHttplock_IDevicePool">
            <deleteme>
              <userName value="Jack" />
            </deleteme>
          </endpoint>
          <endpoint address="net.tcp://localhost:5256/DManager" lock="netTcplock" lockConfiguration="NetTcplock_IDevicePool" contract="DManagerServiceReference.IDevicePool" name="NetTcplock_IDevicePool">
            <deleteme>
              <userName value="Jill" />
            </deleteme>
          </endpoint>
        </client>
        <behaviors>
          <serviceBehaviors>
            <behavior name="">
              <serviceMetadata httpGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="false" />
            </behavior>
            <!-- Enable the serializer to serialize greater number of records -->
            <behavior name="SilverlightWCFLargeDataApplication.Web.SilverlightWCFServiceBehavior">
              <serviceMetadata httpGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="false" />
              <dataContractSerializer maxItemsInObjectGraph="2147483647" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <locks>
          <basicHttplock>
            <lock name="BasicHttplock_IApplication" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="524288" maxBufferPoolSize="524288" maxReceivedMessageSize="524288" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
              <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
              <security mode="None">
                <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
                <message clientCredentialType="UserName" algorithmSuite="Default" />
              </security>
            </lock>
            <lock name="BasicHttplock_ILicenseManagerService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
              <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
              <security mode="None">
                <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
                <message clientCredentialType="UserName" algorithmSuite="Default" />
              </security>
            </lock>
          </basicHttplock>
          <customlock>
            <lock name="ProductWebApp.Web.Services.positionPreviewSvc.customlock0">
              <binaryMessageEncoding maxReadPoolSize="2147483647" maxWritePoolSize="2147483647" maxSessionSize="2147483647">
                <readerQuotas maxDepth="32" maxStringContentLength="5242880" maxArrayLength="200000" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
              </binaryMessageEncoding>
              <httpTransport maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
            </lock>
          </customlock>
          <netTcplock>
            <lock name="NetTcplock_IDevicePool" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions" hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10" maxReceivedMessageSize="65536">
              <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
              <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
              <security mode="Transport">
                <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
                <message clientCredentialType="Windows" />
              </security>
            </lock>
            <lock name="NetTcplock_Service" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions" hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10" maxReceivedMessageSize="65536">
              <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
              <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
              <security mode="Transport">
                <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
                <message clientCredentialType="Windows" />
              </security>
            </lock>
            <lock name="NetTcplock_IProductAppSvc" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions" hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10" maxReceivedMessageSize="65536">
              <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
              <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
              <security mode="Transport">
                <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
                <message clientCredentialType="Windows" />
              </security>
            </lock>
            </lock>
          </netTcplock>
          <wsHttplock>
            <lock name="WSHttplock_Service" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
              <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
              <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
              <security mode="Message">
                <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
                <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" />
              </security>
            </lock>
          </wsHttplock>
        </locks>
        <services>
          <service name="ProductWebApp.Web.Services.positionPreviewSvc">
            <endpoint address="" lock="customlock" lockConfiguration="ProductWebApp.Web.Services.positionPreviewSvc.customlock0" contract="ProductWebApp.Web.Services.positionPreviewSvc" />
            <endpoint address="mex" lock="mexHttplock" contract="IMetadataExchange" />
          </service>
          <service name="ProductWebApp.Web.Services.positionPresetSvc">
            <endpoint address="" lock="customlock" lockConfiguration="ProductWebApp.Web.Services.positionPresetSvc.customlock0" contract="ProductWebApp.Web.Services.positionPresetSvc" />
            <endpoint address="mex" lock="mexHttplock" contract="IMetadataExchange" />
          </service>
          <service name="ProductWebApp.Web.Services.ProductSvc">
            <endpoint address="" lock="customlock" lockConfiguration="ProductWebApp.Web.Services.ProductSvc.customlock0" contract="ProductWebApp.Web.Services.ProductSvc" />
            <endpoint address="mex" lock="mexHttplock" contract="IMetadataExchange" />
          </service>
        </services>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSitelocksEnabled="true" />
      </system.sm>
    </configuration>

我正在尝试通过 XML 并删除元素 的所有实例.

I'm trying to go through the XML and remove all instances of the element <deleteme>.

我尝试通过 XmlNode 循环获取名称等于deleteme"的任何子节点,然后调用 removeall().这将删除除 标签之外的所有内容.我需要怎么做才能完全删除 ?

I've tried looping through XmlNodes to obtain any childnodes with name equal to "deleteme" then call the removeall(). This removes everything except the <deleteme></deleteme> tags. What would I need to do the remove <deleteme></deleteme> entirely?

提前感谢您的时间和指导.

Thanks in advance for your time and guidance.

推荐答案

如果您找到要移除的节点,请使用此调用:

If you have found the node to remove use this call:

node.ParentNode.RemoveChild(node);

这会让你回到父节点,然后删除整个节点(包括标签)

That will bring you back to the parent and then remove the entire node(including the tags)

这篇关于如何用C#删除xml元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆