How can I build XML in C#?

前端 未结 9 1852

How can I generate valid XML in C#?

9条回答
  •  耶瑟儿~
    2020-11-22 06:50

    The best thing hands down that I have tried is LINQ to XSD (which is unknown to most developers). You give it an XSD Schema and it generates a perfectly mapped complete strongly-typed object model (based on LINQ to XML) for you in the background, which is really easy to work with - and it updates and validates your object model and XML in real-time. While it's still "Preview", I have not encountered any bugs with it.

    If you have an XSD Schema that looks like this:

      
         
          
            
            
          
           
           
         
      
    

    Then you can simply build XML like this:

    RootElement rootElement = new RootElement;
    rootElement.Element1 = "Element1";
    rootElement.Element2 = "Element2";
    rootElement.Attribute1 = 5;
    rootElement.Attribute2 = true;
    

    Or simply load an XML from file like this:

    RootElement rootElement = RootElement.Load(filePath);
    

    Or save it like this:

    rootElement.Save(string);
    rootElement.Save(textWriter);
    rootElement.Save(xmlWriter);
    

    rootElement.Untyped also yields the element in form of a XElement (from LINQ to XML).

提交回复
热议问题