开发者

How to find XSD root element in C#

Good day.

As i know. There is a root element in XML file.

But from the XSD file structure, it is not easy to get the root element value. Is there any method to do it?

(I wouldn't like to take use of hard code to find XSD root element value in my开发者_Python百科 project. i want to find the root element of "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>

thank you.


Whilst a single document can only contain one root element, as XSD can actually define multiple valid root elements.

If you only genuinely want a single type to be valid as a root element, then it should be the only type referenced as an <element>.

In your schema above, for example, the DocumentInfo and Prerequisite nodes are valid root elements too. To restrict your schema to have just a single, valid root node, replace your DocumentInfo and Prerequisite elements with simple complexType definitions:

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

UPDATE: To access the name of an element, you just need to look at the Name property on the 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
    }
}


I believe

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜