1

这是我的xml:

<application name="Test Tables">
<test>
  <xs:schema id="test" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">   
  </xs:schema> 
</test>
</application>

如何在<application>不删除节点的情况下删除<test>节点?

4

3 回答 3

1

好的,所以可能不是我的最佳答案,但希望这符合您的需要,或者给您一个良好的起点。首先,我假设您使用的是 C#。因此,我这样做的方式是使用要删除的节点并选择其子节点并使用它们来创建新的 XDocument。可能有一种更简洁的方法使用 Linq 来实现这一点,但如果我能看到它,我该死的!无论如何,希望这会有所帮助:

var doc = XDocument.Load(@".\Test1.xml");

var q = (from node in doc.Descendants("application")
        let attr = node.Attribute("name")
        where attr != null && attr.Value == "Test Tables"
        select node.DescendantNodes()).Single();

var doc2 =  XDocument.Parse(q.First().ToString());

我使用这个 SO 帖子作为我的指南:如何使用 C# 从 XML 文件中删除节点

快乐的编码,
干杯,
克里斯。

于 2012-02-01T10:21:49.413 回答
0

使用 XSLT,您可以这样做:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="application">
    <xsl:apply-templates select="test"/>
  </xsl:template>

  <xsl:template match="node() | @*">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
于 2012-02-01T09:49:27.703 回答
0

嗯,就是这样;

static void Main(string[] args)
    {
        string doc = @"
                    <application name=""Test Tables"">
                    <test>
                      <xs:schema id=""test"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema""                         xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"">   
                      </xs:schema> 
                    </test>
                    </application>
                    ";
        XDocument xDoc = XDocument.Parse(doc);
        Console.Write(xDoc.ToString());
        Console.ReadLine();

        string descendants = xDoc.Descendants("application").DescendantNodes().First().ToString();
        xDoc = XDocument.Parse(descendants);
        Console.Write(xDoc.ToString());
        Console.ReadLine();
    }

虽然我有点好奇你为什么要这样做......

于 2012-02-01T10:20:51.457 回答