How can I load .xsd file to track relationships(nesting) between elements? - c#

I know, where is XmlSchema class in dot net, but it does not allow to load file into it. Is there a clean solution to load xsd file and travel between elements?

You need to use XmlSchemaSet, e.g.:
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(targetNamespace, schemaUri);
schemaSet.Compile();
foreach(XmlSchemaElement element in schemaSet.GlobalElements.Values)
{
// do stuff...
}
EDIT: Sorry for not being clearer.
Where the comment says // do stuff..., what you need to do is traverse the inherited types of each element, which are available under XmlSchemaElement.SchemaType, and the inline type of the element, which is available under XmlSchemaElement.ElementSchemaType.
The MSDN does contain all the the information you're after, but it is somewhat maze-like and requires digging around plus a bit of trial-and-error to work it out.
As per my comment, the following class from one of my open-source side-projects may be of use to you here:
http://bitbucket.org/philbooth/schemabrute/src/tip/LibSchemaBrute/Navigator.cs

I suggest checking out this tool: http://www.altova.com/xmlspy.html. You can create a data model from any XSD file. I've used it in many XML projects.

Related

Smart way of changing json conversion to xml and keep setup

I have already deserialized a json-file to c#-objects. This has been done by the following:
JsonSerializer<FooClass>().DeserializeFromString(json)
and it all works well. I now want to change the json to xml and do the exact same, keeping all the classes and setup, that has already been made inside the solution.
The conversion from json to xml is easy, but I cant figure out how to deserialize the xml so that I dont need to change a lot of code.
Is it possible to keep the whole setup, but somehow change few lines of code such as
JsonSerializer<FooClass>().DeserializeFromString(json)
to something alike, but that deserializes the xml instead?
I've found the following solutions in here, but they don't seem to solve the problem:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
but the SerializeXmlNode isn't possible?
The other solutions I have found in here use arguments and stuff like that, which again will force me to change some of the setup, which I am not interested in, if possible.
Also I am aware, that a direct transformation from json to xml has its cons, but if we look aside from that and focus on the xml part, then it would be nice.
This because we are writing in xml instead of json from now on and therefore the change needed.
One easy route I can see is to leverage the XmlClass Attributes and use XmlSerializer.

how to verify that an XML file implements a specific schema

This is slightly different from just Schema validation. I'm asking how in C# you can check that not only is the document valid against a schema, but also validate that the schema actually applies to that document. I'd prefer a .NET / C# answer but any answer that fully respects the document standards will suffice.
I am making some assumptions as to what exactly you're looking for.
Having said "a specific schema" to me it means that you have a schema and that you're sifting through XML files trying to understand first if that schema should even be used to validate an XML.
First, I would lay some background... A "schema" could be that which one gets in a single file, or spread across multiple files. With multiple files, there are a couple of relationships possible between the XSD files: include, import, redefine; then there's the including of a schema file without a target namespace, by a schema file with a target namespace (this is typically called chameleon). So instead of "schema" I would prefer to use the term "schema set".
Some things to consider then:
A chameleon XSD in your "schema set" may not be intended to validate an XML having an unqualified document element.
A redefined XSD should not be used to validate matching XML content; the redefining XSD should.
Even though an XSD defines abc as a global element, it may not be acceptable to process XML instances that feature abc as the root element.
The above is to indicate that even though an XML may appear to implement a "specific schema", in itself it doesn't mean it matches the intent the author of the XSD placed in that schema.
Considering the above logic defined and implemented somehow, the verification I would do, as an answer to your question, would be to find the XSD definition of a non-abstract, global element - an XmlSchemaElement - in a specific XmlSchemaSet, using the full qualified name of the root element in the XML I am verifying.
System.Xml.Schema.XmlSchemaSet xset = ...; // Loaded somehow
System.Xml.XmlQualifiedName qn = ...; // LocalName + NamespaceURI
if (xset.GlobalElements.Contains(qn))
{
System.Xml.Schema.XmlSchemaElement el = (System.Xml.Schema.XmlSchemaElement)xset.GlobalElements[qn];
if (!el.IsAbstract)
{
// The XML file may implement the schemata loaded in this schema set.
}
}
I would expect this to at least help you improve your question, if I am off.

XML: read children of an element

I'm looking into the possibility of storing settings in an XML file. Here's a simplified version of my code. You don't see it here, but this code is located inside a try block so that I can catch any XmlException that comes up.
XmlReader fileReader = XmlReader.Create(Path.GetDirectoryName(Application.ExecutablePath) + "\\settings.xml");
// Start reading
while (fileReader.Read())
{
// Only concern yourself with start tags
if (fileReader.IsStartElement())
{
switch (fileReader.Name)
{
// Calendar start tag detected
case "Calendar":
//
//
// Here's my question: can I access the children
// of this element here?
//
//
break;
}
}
}
// Close the XML reader
fileReader.Close();
Can I access the children of a certain element on the spot in the code where I put the big comment?
There are applications where using XmlReader to read through an XML document is the right answer. Unless you have hundreds of thousands of user settings that you want to read (you don't) and you don't need to update them (you do), XmlReader is the wrong choice.
Since you're talking about wanting to store arrays and structs in your XML, it seems obvious to me that you want to be using .NET's built in serialization mechanisms. (You can even use XML as the serialization format, if accessing the XML is important to you.) See this page for a starting point.
If you design your settings classes properly (which is not hard), you can serialize and deserialize them without having to write code that knows anything about the names and data types of the properties you're serializing. Your code that accesses the settings will be completely decoupled from the implementation details of how they are persisted, which, as Martha Stewart would say, is a Good Thing.
Check this short article for a solution.
And by the way, you should use LINQ to XML if you want to work easy with XML (overview).
You can use any of the following methods on XmlReader:
ReadSubtree()
ReadInnerXml()
ReadOuterXml()
ReadStartElement()
to read the child content. Which one you use depends on exactly what you wish to do with said child content.
App.config and create a custom section.
App.Config and Custom Configuration Sections

Parsing an XML file -options?

I'm developing a system to pick up XML attachments from emails, via Exchange Web Services, and enter them into a DB, via a custom DAL object that I've created.
I've manage to extract the XML attachment and have it ready as a stream... they question is how to parse this stream and populate a DAL object.
I can create an XMLTextReader and iterate through each element. I don't see any problems with this other than that I suspect there is a much slicker way. The reader seems to treat the opening tag, the content of the tag and the closing tag as different elements (using reader.NodeType). I expected myValue to be considered one element rather than three. Like I said, I can get round this problem, but I'm sure there must be a better way.
I came across the idea of using an XML Serializer (completely new to me) but a quick look suggested that these can't handle ArrayLists and List (I'm using List).
Again, I'm new to LINQ, but LINQ-to-XML has also been mentioned, but examples I've seen seem rather complex - though that my simply be my lack of familiarity.
Basically, I don't want a cludged system, but I don't want to use any complicated technique with a learning curve, just because it's 'cool'.
What is the simplest and most effective way of translating this XML/Stream in to my DAL objects?
XML Sample:
<?xml version="1.0" encoding="UTF-8"?>
<enquiry>
<enquiryno>100001</enquiryno>
<companyname>myco</companyname>
<typeofbusiness>dunno</typeofbusiness>
<companyregno>ABC123</companyregno>
<postcode>12345</postcode>
<contactemail>me#example.com</contactemail>
<firstname>My</firstname>
<lastname>Name</lastname>
<vehicles>
<vehicle>
<vehiclereg>54321</vehiclereg>
<vehicletype>Car</vehicletype>
<vehiclemake>Ford</vehiclemake>
<cabtype>n/a</cabtype>
<powerbhp>130</powerbhp>
<registrationdate>01/01/2003</registrationdate>
</vehicle>
</vehicles>
</enquiry>
Update 1:
I'm trying to deserialize, based on Graham's example. I think I've set up the DAL for serialization, including specifying [XmlElement("whatever")] for each property. And I've tried to deserialize using the following:
SalesEnquiry enquiry = null;
XmlSerializer serializer = new XmlSerializer(typeof(SalesEnquiry));
enquiry = (SalesEnquiry)serializer.Deserialize(stream);
However, I get an exception:'There is an error in XML document (2, 2)'. The innerexception states {"<enquiry xmlns=''> was not expected."}
Conclusion (updated):
My previous problem was the fact that the element in the XML file (Enquiry) != the name of the class (SalesEnquiry). Rather than an [XmlElement] attribute for the class, we need an [XmlRoot] attribute instead. For completeness, if you want a property in your class to be ignored during serialization, you use the [XmlIgnore] attribute.
I've successfully serialized my object, and have now successfully taken the incoming XML and de-serialized it into a SalesEnquiry object.
This approach is far easier than manually parsing the XML. OK, there has been a steep learning curve, but it was worth it.
Thanks!
If your XML uses a schema (i.e. you're always going to know what elements appear, and where they appear in the tree), you could use XmlSerializer to create your objects. You'd just need some attributes on your classes to tell the serializer what XML elements or attributes they correspond to. Then you just load up your XML, create a new XmlSerializer with the type of the .NET object you want to create, and call the Deserialize method.
For example, you have a class like this:
[Serializable]
public class Person
{
[XmlElement("PersonName")]
public string Name { get; set; }
[XmlElement("PersonAge")]
public int Age { get; set; }
[XmlArrayItem("Child")]
public List<string> Children { get; set; }
}
And input XML like this (saved in a file for this example):
<?xml version="1.0"?>
<Person>
<PersonName>Bob</PersonName>
<PersonAge>35</PersonAge>
<Children>
<Child>Chris</Child>
<Child>Alice</Child>
</Children>
</Person>
Then you create a Person instance like this:
Person person = null;
XmlSerializer serializer = new XmlSerializer(typeof(Person));
using (FileStream fs = new FileStream(GetFileName(), FileMode.Open))
{
person = (Person)serializer.Deserialize(fs);
}
Update:
Based on your last update, I would guess that either you need to specify an XmlRoot attribute on the class that's acting as your root element (i.e. SalesEnquiry), or the XmlSerializer might be a bit confused that you're referencing an empty namespace in your XML (xmlns='' doesn't seem right).
XmlSerializer does support arrays & lists... as long as the contained type is serializable.
I have found Xsd2Code very helpful for this kind of thing: http://xsd2code.codeplex.com/
Basically, all you need to do is write an xsd file (an XML schema file) and specify a few command line switches. Xsd2Code will automatically generate a C# class file that contains all the classes and properties plus everything needed to handle the serialization. It's not a perfect solution as it doesn't support all aspects of XSD, but if your XML files are relatively simple collections of elements and attributes, it should be a nice short-cut for you.
There's another similar project on Codeplex called Linq to XSD (http://linqtoxsd.codeplex.com/), which was designed to enforce the entire XSD specification, but last time I checked, it was no longer being supported and not really ready for prime time. Thought it was worth a mention, though.

Creating something similar to System.ServiceModel.Syndication using .NET 3.5

If I am dealing with several standard xml formats what would be the best practice way of encapsulating them in C# 3.5? I'd like to end up with something similar to the System.ServiceModel.Syndication namespace.
A class that encapsulates the ADF 1.0 XML standard would be one example. It has the main XML root node, 6 child elements, 4 of which are required IIRC, several required and optional elements and attributes further down the tree. I'd like the class to create, at a minimum, the XML for all the required pieces all the way up to a full XML representation. (Make sense).
With LINQ 4 XML and extension classes, etc, etc, there has to be some ideas on quickly generating a class structure for use. Yes? No? :)
Am not sure if I gave enough details to get one correct answer but am willing to entertain ideas right now.
TIA
XML serialization seems a good approach. You could even use xsd.exe to generate the classes automatically...
EDIT
Note that the class names generated by the tool are usually not very convenient, so you might want to rename them. You might also want to change arrays of T to List<T>, so that you can easily add items where needed.
Assuming the class for the root element is named ADF, you can load an ADF document as follows :
ADF adf = null;
XmlSerializer xs = new XmlSerializer(typeof(ADF));
using (XmlReader reader = XmlReader.Create(fileName))
{
adf = (ADF)xs.Deserialize(reader);
}
And to save it :
ADF adf = ...; // create or modify your document
...
XmlSerializer xs = new XmlSerializer(typeof(ADF));
using (XmlWriter writer = XmlWriter.Create(fileName))
{
xs.Serialize(writer, adf);
}
Why not just follow the pattern of the SyndicationFeed object in the Syndication namespace? Create a class that takes in a Uri to the xml document or just takes in the document fragment.
Then parse the document based on your standards (this parsing can be done using LinqToXml if you wanted to, though regEx might be faster if you are comfortable with them). Throw exceptions or track errors appropriately when the document doesn't pass the specification rules.
If the document passes the parse step then break the pieces of the document out into public getter properties of your object. Then return the fully hydrated object back to the consumer for use
Seems pretty straight forward to me. Is that what you are after or are you looking for something more than this?

Categories