Solved

Creating XML file with schema

Posted on 2004-03-31
13
4,984 Views
Last Modified: 2013-11-19
I am working with XML file which looks like:

<?xml version="1.0"?>
<!DOCTYPE root [
  <!ELEMENT Student ANY>
  <!ATTLIST Student ID ID #REQUIRED>
]>
<Students>
  <Student ID="104">
    <Name>Vicki Tyson</Name>
     <Grades>
       <MFC>48</MFC>
       <ATL>63</ATL>
       <Winsock>72</Winsock>
    </Grades>
  </Student>
  ...
</Students>

I have the program that can open, update and save files with such structure. It works by such way:

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);   // now document contains both data and schema
// make changes in XmlDocument ...
xmlDocument.Save(fileName);

Saved document contains both schema and data. Now I want to add "New" function to the program, which creates new file. In this case program should work by such way:

XmlDocument xmlDocument = new XmlDocument();
// make changes in XmlDocument (add nodes)
xmlDocument.Save(fileName);

However, document created by such way doesn't contain schema. How can I add XML schema programmatically?
0
Comment
Question by:AlexFM
  • 5
  • 4
  • 2
  • +1
13 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 10723194
There are tutorials for XML schema documents:

XSD How To
http://www.w3schools.com/schema/schema_howto.asp

You could start with these, and learn the syntax rules.  And then look at an XSD file generated for a typed dataset by a DataAdapter.

These nodes are from an existing XSD:

 <?xml version="1.0" standalone="yes" ?>
- <xs:schema id="DataSet1" targetNamespace="http://www.tempuri.org/DataSet1.xsd" xmlns:mstns="http://www.tempuri.org/DataSet1.xsd" xmlns="http://www.tempuri.org/DataSet1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified">
- <xs:element name="DataSet1" msdata:IsDataSet="true">
- <xs:complexType>


Bob
0
 
LVL 12

Expert Comment

by:vascov
ID: 10723348
DataSet ds = new DataSet();

ds.ReadXml( fileName );

MessageBox.Show( ds.GetXmlSchema() )


Another way... drop your file in VS.NET, and then right-click on the xml content and select "Generate Schema". From then on tweak that schema.
(if you want, you can further generate a strong typed dataset (right-click on the schema, and "Generate DataSet", or you can also use the cmd-line xsd.exe)

hth

Vasco
0
 
LVL 48

Author Comment

by:AlexFM
ID: 10723615
Thanks, but both answers are not related to my question. I don't need to learn XML schema structure, and I don't work with dataset.
My question is: having XmlDocument instance, how can I add to it XML schema programmatically?
I think this is possible, because when XmlDocument instance loads file which contains schema, it keeps it and writes the same schema to file created by Save function.
0
 
LVL 12

Expert Comment

by:vascov
ID: 10723825
Alex, Schema is used to validate a given document, not to prepopulate or something like that.
If all you want is to generate a new schema,
* create a DataSet
* Load the xml from the XmlDocument and ask to save it as:

DataSet ds = new DataSet();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml( "<root/>" );
xmlDoc.DocumentElement.Attributes.Append( xmlDoc.CreateAttribute( "abc", "http://mynamespace" ) );
StringReader sr = new StringReader( xmlDoc.InnerXml );
ds.ReadXml( sr, XmlReadMode.Auto );
StringWriter sw = new StringWriter();
ds.WriteXml( sw, XmlWriteMode.WriteSchema );
MessageBox.Show( sw.ToString() );

hth

Vasco
0
 
LVL 48

Author Comment

by:AlexFM
ID: 10723946
Well, I try to ask again.
Suppose I have such XML file:

<?xml version="1.0"?>
<!DOCTYPE root [
  <!ELEMENT Student ANY>
  <!ATTLIST Student ID ID #REQUIRED>
]>
<Students>
  <Student ID="104">
    <Name>Vicki Tyson</Name>
     <Grades>
       <MFC>48</MFC>
       <ATL>63</ATL>
       <Winsock>72</Winsock>
    </Grades>
  </Student>
</Students>

Program:

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);   // now document contains both data and schema
// add new node to XML document ...
xmlDocument.Save(fileName);

Result:

<?xml version="1.0"?>
<!DOCTYPE root [
  <!ELEMENT Student ANY>
  <!ATTLIST Student ID ID #REQUIRED>
]>
<Students>
  <Student ID="104">
    <Name>Vicki Tyson</Name>
     <Grades>
       <MFC>48</MFC>
       <ATL>63</ATL>
       <Winsock>72</Winsock>
    </Grades>
  </Student>
  <Student ID="105">
    <Name>John</Name>
     <Grades>
       <MFC>48</MFC>
       <ATL>63</ATL>
       <Winsock>72</Winsock>
    </Grades>
  </Student>
</Students>

Other situation: I don't have XML file. Program:

XmlDocument xmlDocument = new XmlDocument();
// add new node to XML document ...
xmlDocument.Save(fileName);

Result:

<?xml version="1.0"?>
<Students>
  <Student ID="105">
    <Name>John</Name>
     <Grades>
       <MFC>48</MFC>
       <ATL>63</ATL>
       <Winsock>72</Winsock>
    </Grades>
  </Student>
</Students>

I want this result:

<?xml version="1.0"?>
<!DOCTYPE root [
  <!ELEMENT Student ANY>
  <!ATTLIST Student ID ID #REQUIRED>
]>
<Students>
  <Student ID="105">
    <Name>John</Name>
     <Grades>
       <MFC>48</MFC>
       <ATL>63</ATL>
       <Winsock>72</Winsock>
    </Grades>
  </Student>
</Students>

I want to do this programmatically:

XmlDocument xmlDocument = new XmlDocument();
// add schema to XML document - how ???
// add new node to XML document ...
xmlDocument.Save(fileName);
0
 
LVL 12

Expert Comment

by:vascov
ID: 10724216
Hi Alex, the sample i sent you does just that.
It will generate Xml Schema though, and i frankly don't know how/if it can generate DTD. (i'm under the impression it wont)

For the sample i sent you before, here's the output:
<NewDataSet>
  <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:app1="http://mynamespace">
    <!--ATTENTION: This schema contains references to other imported schemas-->
    <xs:import namespace="http://mynamespace" schemaLocation="_app1.xsd" />
    <xs:element name="root">
      <xs:complexType>
        <xs:attribute ref="app1:abc" />
      </xs:complexType>
    </xs:element>
    <xs:element name="NewDataSet" msdata:IsDataSet="true">
      <xs:complexType>
        <xs:choice maxOccurs="unbounded">
          <xs:element ref="root" />
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <root d1p1:abc="" xmlns:d1p1="http://mynamespace" />
</NewDataSet>


Vasco
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 48

Author Comment

by:AlexFM
ID: 10730109
Thanks, I found sirprisingly simple way to do this using XmlDocument.LoadXml function.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 10732497
Could you explain how you did it in more detail?

Bob
0
 
LVL 12

Expert Comment

by:vascov
ID: 10733312
I'm also interested,

do you mean that you used XmlDocument.LoadXml to generate inline DTD ?

Vasco
0
 
LVL 12

Expert Comment

by:vascov
ID: 10733686
I don't object closing the question, but i think that an explanation of how (and what) it was solved should be given by Alex.

My suspicion is that Alex used LoadXml do inline the DTD himself, but i'm still curious if that's his question.
If you ended up using LoadXml for that, than i'm glad that eventually my sample hinted you in that direction.

Furthermore, if all you wanted was to generate the DTD yourself than look at XmlDocument.CreateDocumentType...

Vasco

0
 
LVL 48

Author Comment

by:AlexFM
ID: 10738635
This is my code:

        public bool NewDocument()
        {
            try
            {
                xmlDocument = new XmlDocument();

                StringBuilder s = new StringBuilder();
                s.Append("<?xml version=\"1.0\"?>\n");
                s.Append("<!DOCTYPE root[\n");
                s.Append("  <!ELEMENT Student ANY>\n");
                s.Append(" <!ATTLIST Student ID ID #REQUIRED>\n");
                s.Append("]>\n");
                s.Append("<Students>\n");
                s.Append("</Students>");

                xmlDocument.LoadXml(s.ToString());

                fileName = "";
                SetDirty(false);
                RaiseStateChangeEvent();

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(parentForm, String.Format(ex.Message), errorTitle);
            }

            return false;
        }

I know this question looks stupid, and external XML schema should be used instead of inline DTD, but this is what I needed to complete my XML exersize. Thank you for your help, if somebody thinks that his notes were helpful, you can post here and I will accept them.
0
 

Accepted Solution

by:
ee_ai_construct earned 0 total points
ID: 10756874
Closed, 500 points refunded.
ee_ai_construct
Community Support Moderator
(re-order part number xm34)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Total in textboxes 9 35
crm development 2 37
Form design in vb.net 7 19
Closing all open child forms. 4 23
What is Node.js? Node.js is a server side scripting language much like PHP or ASP but is used to implement the complete package of HTTP webserver and application framework. The difference is that Node.js’s execution engine is asynchronous and event…
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now