简体   繁体   中英

How do I validate this kind of xml errors in the c# code?

<?xml version="1.0" encoding="utf-8"?>
<xml>
  <a>str1234</a>xxxx
</xml>

I got this xml file, as you can see, there's "xxxx" after the "a" close tag.

I tried the xmldocument.load() method but it wouldn't throw any exceptions.

I tried to generate a xsd file from this xml, then validate this xml with the generated xsd.

However, it also wouldn't throw any errors.

It is important to understand the difference between valid and well-formed XML .

Commenters have sloppily said that your XML is valid . They actually should not make such a statement without a schema against which to assess validity. They should be saying that your XML is well-formed .

You seem to be concerned that xxxx text as a sibling to an a element is not well formed, but it is perfectly well-formed XML. It might also be valid , if the parent element, xml is defined by a schema to allow mixed-content .

I tried to generate a xsd file from this xml, then validate this xml with the generated xsd.

Well, if you used a tool to generate an XSD from an XML document instance, and the XSD said the XML was valid, then the tool is working as designed.

But when my code loading this kind of .config file,it got stuck.

Just like being well-formed doesn't guarantee validity, it also doesn't guarantee that it meets the needs of any given consuming XML application. A configuration file has rules, perhaps expressed in an XSD, that the XML must follow. These rules are in addition to being well-formed (the rules that a parser requires in order to parse XML).

See also How to validate xml code file though .NET? + How would I do it if I use XML serialization?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM