How to find XSD root element in C #

Good afternoon.

As I know. There is a root element in the XML file.

But from the structure of the XSD file, getting the value of the root element is not so simple. Is there any way to do this?

(I would not want to use hard code to find the value of the root XSD element in my project. I want to find the root element "RootValueHere"

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="RootValueHere"> <xsd:complexType> <xsd:sequence> <xsd:element ref="DocumentInfo" minOccurs="1" maxOccurs="1" /> <xsd:element ref="Prerequisite" minOccurs="1" maxOccurs="1" /> </xsd:sequence> </xsd:complexType> </xsd:element> <!-- Element of DocumentInfo --> <xsd:element name="DocumentInfo"> <xsd:complexType> <xsd:attribute name="Name" type="xsd:string" /> <xsd:attribute name="Description" type="xsd:string" /> <xsd:attribute name="Creator" type="xsd:string" /> <xsd:attribute name="CreateTime" type="xsd:string" /> </xsd:complexType> </xsd:element> <!-- Element of Prerequisite --> <xsd:element name="Prerequisite"> <xsd:complexType> <xsd:sequence> <xsd:element name="Type" type="Prerequisite.Type.type" minOccurs="1" maxOccurs="1" /> <xsd:element name="Miscellaneous" type="Prerequisite.Misc.type" minOccurs="0" maxOccurs="1" /> </xsd:sequence> </xsd:complexType> </xsd:element> 

thanks.

+4
source share
2 answers

While a single document can contain only one root element, since the XSD can actually define several valid root elements .

If you really want one type to be valid as the root element, it should be the only type referenced by <element> .

In the above diagram, for example, DocumentInfo and Prerequisite nodes are also valid root elements. To limit your schema to only one valid root node, replace the DocumentInfo and Prerequisite elements with simple complexType definitions:

 <xsd:complexType name="DocumentInfoType"> ... </xsd:complexType> <xsd:complexType name="Prerequisite"> .... </xsd:complexType> 

UPDATE: to access the element name you just need to look at the Name property in XmlElement:

 XmlDocument doc = new XmlDocument(); doc.Load("D:\\schema.xsd"); // Load the document from the root of an ASP.Net website XmlElement schemaElement = doc.DocumentElement; // The root element of the schema document is the <schema> element string elementName = schemaElement.LocalName; // This will print "schema" foreach (XmlNode ele in schemaElement.ChildNodes) { if (ele.LocalName == "element") { // This is a valid root node // Note that there will be *more than one* of these if you have multiple elements declare at the base level } } 
+5
source

I believe

 XmlDocument myDocument = new XmlDocument("my.xml"); myDocument.DocumentElement(); //gets root document node 
+1
source

All Articles