PDA

View Full Version : XmlTextReader in C#



mickey
25th June 2010, 17:38
Hello,
I must write a little parser (or scanner) for my own tag language; an example of it:


<html>
<head></head>
<body>
<using xmlns:namespace="myfile" />
myText
<p><namespace:myComponent Attribs="val"> //it crashes on 'namespace:myCOmponent'
</body>
</html>

As you can see there is a namaspace that is declared in a my own way (using the keyword 'using'); now, using XmlReader like it is, doens't work (exception occurs since standard XML needs a different namespace declaration);
so I must to know if there is a way to cope this problem; here below my parser and an attempt to cope that namespace (but it doesn't work at all):


public Parser(string fileContent) {
_settings.ConformanceLevel = ConformanceLevel.Fragment;
_settings.IgnoreWhitespace = true;
_settings.IgnoreComments = true;
_textReader = XmlReader.Create(fileContent, _settings);
_textReader.Read();
XmlNodeType nType = _textReader.NodeType;
while (_textReader.Read()) {
switch (_textReader.NodeType) {
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + _textReader.Name);
Console.WriteLine(">");
if (_textReader.Name == "using") {
while (_textReader.MoveToNextAttribute()) { //attempt to do that
if (_textReader.Prefix == "xmlns") {
Console.WriteLine("<{0}:{1}>", _textReader.Prefix, _textReader.LocalName);
nsmanager = new XmlNamespaceManager(_textReader.NameTable);
nsmanager.AddNamespace(_textReader.LocalName, "mynamespace");
}
}
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine(_textReader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + _textReader.Name);
Console.WriteLine(">");
break;
}
}

SixDegrees
28th June 2010, 00:25
XML is widely used because it is extensively standardized. Standards are good for you and everyone else for just this reason.

The solution here would be to use standards compliant XML. If you want to depart from XML, you won't be able to use an XML parser. Feel free to invent your own markup language, and write your own parser for it.