c# - 通过使用 xpath 在 c# 中过滤现有文档来创建新的 XMLDocument

标签 c# linq xslt xpath xmldocument

我有一种情况,我从外部公司收到一个 XML(文档)文件。我需要过滤文档以删除所有我不感兴趣的数据。 该文件大约 500KB,但会经常被请求。

假设以下文件:

<dvdlist>
  <dvd>
    <title>title 1</title>
    <director>directory 2</director>
    <price>1</price>
    <location>
      <city>denver</city>
    </location>
  </dvd>
  <dvd>
    <title>title 2</title>
    <director>directory 2</director>
    <price>2</price>
    <location>
      <city>london</city>
    </location>
  </dvd>
  <dvd>
    <title>title 3</title>
    <director>directory 3</director>
    <price>3</price>
    <location>
      <city>london</city>
    </location>
  </dvd>
</dvdlist>

我需要的只是根据 city = london 过滤文档,以便以这个新的 XML 文档结束

<dvdlist>
  <dvd>
    <title>title 2</title>
    <director>directory 2</director>
    <price>2</price>
    <location>
      <city>london</city>
    </location>
  </dvd>
  <dvd>
    <title>title 3</title>
    <director>directory 3</director>
    <price>3</price>
    <location>
      <city>london</city>
    </location>
  </dvd>
</dvdlist>

我试过以下方法

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Development\Website\dvds.xml");
XmlNode node = doc.SelectSingleNode("dvdlist/dvd/location/city[text()='london']");

任何帮助或链接将不胜感激

谢谢

最佳答案

XPath 是一种选择表达式语言——它从不修改它操作的 XML 文档

因此,为了获得所需的新 XML 文档,您需要使用 XML DOM(不推荐)或对 XML 文档应用 XSLT 转换。后者是推荐的方法,因为 XSLT 是一种专门为树转换设计的语言。

在 .NET 中可以使用 XslCompiledTransform 及其 Transform() 方法。在 relevant MSDN documentation 中阅读有关这些的更多信息.

XSLT 转换本身非常简单:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="dvd[not(location/city='london')]"/>
</xsl:stylesheet>

Here ,您可以找到完整的代码示例,了解如何将转换结果作为 XmlDocument(或者如果需要,作为 XDocument)。

关于c# - 通过使用 xpath 在 c# 中过滤现有文档来创建新的 XMLDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3897000/

相关文章:

c# - 检查字符串数组元素只包含另一个数组中的元素

mysql - C# SQL Linq 获取所有重复项

java - XML 的 XSL 排序

xslt - 从节点结构生成带有 xsl 的面包屑路径

c# - IDictionary 到字符串

C# UDP Socket 需要时间将数据发送到未知 IP

c# - Entity Framework 。 SQL 分组依据到 EF 分组依据

variables - xslt - 如何创建一个具有动态确定长度的空格字 rune 本内容的变量,该变量将表现良好

c# - 模拟错误域中的用户不会抛出异常

c# - 如何找到我刚刚用 protobuf-net 反序列化的消息?