C # xml read / write / xpath without using XmlDocument

I am reorganizing some code in an existing system. The goal is to remove all instances of XmlDocument to reduce memory. However, we use XPath to manipulate xml when certain rules apply. Is there a way to use XPath without using a class that loads the entire document into memory? We replaced all other instances of XmlTextReader, but they only worked because XPath does not exist, and reading is very simple.

Some of XPath use the values ​​of other nodes to make decisions. For example, the value of a node message may be based on the value of the sum of a node, so you must access multiple nodes at the same time.

+3
source share
4 answers

If the XPATH expression is based on access to multiple nodes, you just need to read the XML in the DOM. However, two things. First, you don’t need to read all of this in the DOM, just the part you are requesting. Secondly, which DOM you use matters; XPathDocument is read-only and tuned for XPATH request speed, unlike the more general-purpose, but expensive XmlDocument.

+3
source

I suggest using System.Xml.Linq.XDocument is also forbidden? Otherwise, it would be a good choice, as it is faster than XmlDocument (as I recall).

+1
source

XPath , :

//address[/states/state[@code=current()/@code]='California']

//item[@id != preceding-sibling/item/@id]

, XPath . XPath .

0
source

The way to do this is to use an XPathDocument that can accept a stream, so you can use a StringReader.

This returns the value in direct read mode without the overhead of loading the entire XML DOM into memory using an XmlDocument.

Here is an example that returns the value of the first node that satisfies the XPath request:

public string extract(string input_xml)
    {
        XPathDocument document = new XPathDocument(new StringReader(input_xml));
        XPathNavigator navigator = document.CreateNavigator();
        XPathNodeIterator node_iterator = navigator.Select(SEARCH_EXPRESSION);
        node_iterator.MoveNext();
        return node_iterator.Current.Value;
    }
0
source

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


All Articles