Reputation: 5
this is my situation:
public static string ReadFromLine(int lineNumber, params string[] searchedAttribute)
{
//XmlTextReader reader = new XmlTextReader(xmlFilePath);
XmlReaderSettings settings = new XmlReaderSettings();
settings.LineNumberOffset = lineNumber;
settings.DtdProcessing = DtdProcessing.Parse;
FileStream fs = new FileStream(xmlFilePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
XmlReader reader = XmlReader.Create(fs, settings);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == searchedAttribute[0] || reader.Name == searchedAttribute[1])
{
if(reader.Name == searchedAttribute[0])
reader.MoveToAttribute(searchedAttribute[0]);
else
reader.MoveToAttribute(searchedAttribute[1]);
string currentAttributeValue = reader.ReadElementString();
return currentAttributeValue;
}
}
return "notFound";
}
In the method I want to read a xml file from line that is passed in the variable "linenumber".
Unfortunately, despite using my settings according to documentation, my reader starts at line 1 every time.
Appreciate any ideas how to solve it or another solutions.
Upvotes: 0
Views: 791
Reputation: 18023
Unfortunately, despite using my settings according to documentation...
There must be some misunderstanding here. An XmlReader
always starts from the current position of the passed Stream
, TextReader
, etc.
All what LineNumberOffset
does is just an adjustment of the reported line number (if there is any error during the processing, for example).
A possible (but not quite recommended) solution can be if you embed your FileStream
into a StreamReader
, read lineNumber
of lines, and then create an XmlReader
passing the StreamReader
at the current position to the XmlReader.Create(TextReader,XmlReaderSettings)
overload:
using var stream = File.OpenRead(xmlFilePath);
// skipping lineNumber of lines
var streamReader = new StreamReader(stream);
for (int i = 0; i < lineNumber; i++)
streamReader.ReadLine();
XmlReader xmlReader = XmlReader.Create(sreamReader, settings);
But in fact a more preferable (and formatting-proof) solution would be to read the whole XML into anXDocument
and then navigate in the content by LINQ to XML.
Upvotes: 1