Create a new XMLDocument by filtering an existing document in C # using xpath

I have a situation where I get an XML file (document) from an external company. I need to filter a document to delete all the data that I am not interested in. The file is about 500 KB, but will be requested very often.

let's say the following file:

<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>

I just need to filter the document based on city ​​= london to complete this new XML document

<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>

I tried the following

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

Any help or links would be appreciated

thank

+3
source share
2 answers

XPath - - XML- (s), .

, XML-, XML DOM ( ), XSLT XML. , XSLT - , .

.NET XslCompiledTransform (). . MSDN.

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>

, XmlDocument ( , , XDocument).

+1

LINQ to XML.

//load the document
var document = XDocument.Load(@"C:\Development\Website\dvds.xml");
//get all dvd nodes
var dvds = document.Descendants().Where(node => node.Name == "dvd");
//get all dvd nodes that have a city node with a value of "london"
var londonDVDs = dvds.Where(dvd => dvd.Descendants().Any(child => child.Name == "city" && child.Value == "london"));
0

Source: https://habr.com/ru/post/1768770/


All Articles