473,804 Members | 2,079 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

does my stream contain valid XML?

LJB
If I read a text file from disk into a stream how can I tell if it might
already be valid XML? I'm writing an app to compare two XML files one of
which may need conversion to XML first. My app will do the conversion when
necessary. I plan to call XMLdiffView, from
http://msdn2.microsoft.com/en-us/library/aa302295.aspx, to generate the
differences report.

thanks
LJB
May 2 '07 #1
3 2442
<"LJB" <.>wrote:
If I read a text file from disk into a stream how can I tell if it might
already be valid XML? I'm writing an app to compare two XML files one of
which may need conversion to XML first. My app will do the conversion when
necessary. I plan to call XMLdiffView, from
http://msdn2.microsoft.com/en-us/library/aa302295.aspx, to generate the
differences report.
The easiest way would be to just load the stream as an XML document. If
you can load it without an exception occurring, it's valid XML. I know
it's not exactly elegant, but it's simple...

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 2 '07 #2
Perhaps attach an XmlReader, MoveToContent() and Skip() the whole
thing? IIRC this will still throw an exception if it is invalid...
(but you'd need to verify by testing).

If your stream is seekable this is a pinch; if not, and your stream is
repeatable then simply open it twice in a row. My post just bombed and
I can now see Jon's reply; XmlDocument will also work, but could
perhaps be a hog for large xml. It would be perfectly adequate for
small-to-moderate size though.

Marc

May 2 '07 #3
If I read a text file from disk into a stream how can I tell if it might
already be valid XML? I'm writing an app to compare two XML files one of
which may need conversion to XML first. My app will do the conversion when
necessary. I plan to call XMLdiffView, from
http://msdn2.microsoft.com/en-us/library/aa302295.aspx, to generate the
differences report.
See members "ValidationEven tHandler", "ValidationType " and "ValidationFlag s" in class "XmlReaderSetti ngs". Here's a cut-and-paste example:

public void LoadFromFile(st ring fileName)
{
// ...

XmlReaderSettin gs settings = new XmlReaderSettin gs();
settings.Schema s.Add(null, GetSchemaFullFi leName()); // ".xsd" file
settings.Valida tionType = ValidationType. Schema;
settings.Valida tionFlags |= XmlSchemaValida tionFlags.Repor tValidationWarn ings;

///////////////////////////////////////////////////////////////
// Assign an anonymous delegate to trap any schema violations
// when "ReadXml()" is called further below. That is, the
// delegate will be invoked if "fileName" doesn't conform to
// the schema found in the ".xsd" file plugged in above. Note
// that the delegate simply throws an exception on the first
// problem encountered.
///////////////////////////////////////////////////////////////
settings.Valida tionEventHandle r +=
delegate(object sender, ValidationEvent Args args)
{
throw new InvalidFileExce ption(fileName, args.Exception) ;
};

// Create a reader for "fileName" using the above settings
using (XmlReader reader = XmlReader.Creat e(fileName, settings))
{
try
{
////////////////////////////////////////////////////////////
// Read the file into the calling object (us). Note that
// the delegate above will be called if the file doesn't
// conform to the schema file we plugged in earlier. Other
// errors are also possible however but these will normally
// be of type "XmlExcepti on" so we specifically catch that
// below and re-throw it as our own custom exception. Note
// that such errors are usually XML syntax errors however
// so they won't normally be encountered unless someone
// has mucked with the file or otherwise passed some other
// invalid XML file.
////////////////////////////////////////////////////////////
ReadXml(reader) ;
}
catch (XmlException exception)
{
throw new InvalidFileExce ption(fileName, exception);
}
finally
{
reader.Close();
}
}

// ...
}

May 2 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1930
by: carl bloc | last post by:
Have this much done but need help with this bit of code: allow user to modify existing draw data. I think I need a counter to give week numbers so the user can select a week number rather than a date. I need to view data for a selected week given the week number or date. need some controls on not allowing the ball number to go >49 or <0 and no duplicates.
6
1590
by: William Payne | last post by:
Hi, I have a function declared as: void foo(const std::string& s, std::ostream& verbose_output); I want foo() to write a lot of data to the ostream if it's a valid stream. If it's valid or not should depend on user input (command line arguments actually). If the user decides he/she wants verbose output, I will pass std::cout as the last argument when calling foo(). But what should I pass if the user doesn't want any output? And how...
2
3433
by: Daniel Goldman | last post by:
Hi, Any advice about both a BinaryReader and BinaryWriter containing same FileStream at same time? Like: Stream fs = new FileStream("output.dbf", FileMode.Create); BinaryReader br = new BinaryReader(fs); BinaryWriter bw = new BinaryWriter(fs); /* BinaryWriter writes, flushes, etc */ /* BinaryReader seeks, reads, etc */
1
12067
by: BH | last post by:
I'm trying a simple object serialization and deserialization, and keep getting this error: System.Runtime.Serialization.SerializationException: Binary stream does not contain a valid BinaryHeader, 0 possible causes, invalid stream or object version change between serialization and deserialization. Here's my code. it does nothing but to serialize a DataTable object into a byte array, and then read the byte array back for...
5
2111
by: Barry Anderberg | last post by:
I'm using a tool by Sci-Tech called the .NET Memory Profiler. We have a massive .NET/C# application here and it has been exhibiting memory leak behavior for some time. Attempting to remedy the problems I am employing the aforementioned software in trying to track down the problems. After an hour or so of program execution, a snapshot of the managed heap shows 27,025 BinaryReader objects as having been garbage collected but never...
5
3070
by: Daniel Corbett | last post by:
I am trying to save a file dynamically created in a webpage. I get the following headers, but cannot figure out how to save the attachment. I am basically trying to replicate what internet explorer would do in this case. The headers I am getting are: Headers {Content-Disposition: attachment; filename="dynamic_file.mdb" Connection: close Cache-Control: private Content-Type: application/octet-stream
0
1929
by: Vince Filby | last post by:
Hi, We are working with distributing Lucene.net. We have Master Index Server which takes responsibility of distributing the index searching to multiple Index Servers by calling the remote method Search(...) of the Index Server. It is when the Master Server de-serializing the response message from the Index Server, we got the following SerializationException. The Search method is overloaded:
36
4553
by: puzzlecracker | last post by:
Would someone explain why this declaration is illegal: class Sample<T> where T : Stream, class
7
16664
by: phpnewbie26 | last post by:
I'm not sure what this error means and was wondering if anyone knew what the problem is and how it can be fixed. This error comes out multiple times but each time the number is different. Warning: fclose(): 15 is not a valid stream resource in /mnt/raid/www/intra/admin/ts2/test2.php on line 174 Warning: fclose(): 20 is not a valid stream resource in /mnt/raid/www/intra/admin/ts2/test2.php on line 174 Warning: fclose(): 25 is not a...
0
9714
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10350
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10351
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9174
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6866
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5534
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4311
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.