Reading Xml with XmlReader in C#

后端 未结 7 2172
南旧
南旧 2020-11-22 09:02

I\'m trying to read the following Xml document as fast as I can and let additional classes manage the reading of each sub block.


             


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 09:48

    The following example navigates through the stream to determine the current node type, and then uses XmlWriter to output the XmlReader content.

        StringBuilder output = new StringBuilder();
    
        String xmlString =
                @"
                
                
                  test with a child element  stuff
                ";
        // Create an XmlReader
        using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
        {
            XmlWriterSettings ws = new XmlWriterSettings();
            ws.Indent = true;
            using (XmlWriter writer = XmlWriter.Create(output, ws))
            {
    
                // Parse the file and display each of the nodes.
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            writer.WriteStartElement(reader.Name);
                            break;
                        case XmlNodeType.Text:
                            writer.WriteString(reader.Value);
                            break;
                        case XmlNodeType.XmlDeclaration:
                        case XmlNodeType.ProcessingInstruction:
                            writer.WriteProcessingInstruction(reader.Name, reader.Value);
                            break;
                        case XmlNodeType.Comment:
                            writer.WriteComment(reader.Value);
                            break;
                        case XmlNodeType.EndElement:
                            writer.WriteFullEndElement();
                            break;
                    }
                }
    
            }
        }
        OutputTextBlock.Text = output.ToString();
    

    The following example uses the XmlReader methods to read the content of elements and attributes.

    StringBuilder output = new StringBuilder();
    
    String xmlString =
        @"
            
                The Autobiography of Benjamin Franklin
                
                    Benjamin
                    Franklin
                
                8.99
            
        ";
    
    // Create an XmlReader
    using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
    {
        reader.ReadToFollowing("book");
        reader.MoveToFirstAttribute();
        string genre = reader.Value;
        output.AppendLine("The genre value: " + genre);
    
        reader.ReadToFollowing("title");
        output.AppendLine("Content of the title element: " + reader.ReadElementContentAsString());
    }
    
    OutputTextBlock.Text = output.ToString();
    

提交回复
热议问题