diff --git a/snippets/csharp/System.Xml.Schema/XmlSchemaSet/Overview/xml/books.xsd b/snippets/csharp/System.Xml.Schema/XmlSchemaSet/Overview/xml/books.xsd new file mode 100644 index 00000000000..5f9a726fa26 --- /dev/null +++ b/snippets/csharp/System.Xml.Schema/XmlSchemaSet/Overview/xml/books.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/snippets/csharp/System.Xml.Schema/XmlSchemaSet/Overview/xml/booksschemafail.xml b/snippets/csharp/System.Xml.Schema/XmlSchemaSet/Overview/xml/booksschemafail.xml new file mode 100644 index 00000000000..eca0efa8327 --- /dev/null +++ b/snippets/csharp/System.Xml.Schema/XmlSchemaSet/Overview/xml/booksschemafail.xml @@ -0,0 +1,26 @@ + + + + + + Benjamin + Franklin + + + + The Confidence Man + + Herman + Melville + + 11.99 + + + The Gorgias + + Plato + + 9.99 + + + diff --git a/snippets/csharp/System.Xml/XmlReader/Create/factory_rdr_cctor21.cs b/snippets/csharp/System.Xml/XmlReader/Create/factory_rdr_cctor21.cs new file mode 100644 index 00000000000..b728f5eafd6 --- /dev/null +++ b/snippets/csharp/System.Xml/XmlReader/Create/factory_rdr_cctor21.cs @@ -0,0 +1,30 @@ +using System.Xml; + +public class Sample1 +{ + public static void Main() + { + // + // Set the reader settings. + XmlReaderSettings settings = new XmlReaderSettings(); + settings.IgnoreComments = true; + settings.IgnoreProcessingInstructions = true; + settings.IgnoreWhitespace = true; + // + + // + // Create a resolver with default credentials. + XmlUrlResolver resolver = new XmlUrlResolver(); + resolver.Credentials = System.Net.CredentialCache.DefaultCredentials; + + // Set the reader settings object to use the resolver. + settings.XmlResolver = resolver; + + // Create the XmlReader object. + XmlReader reader = XmlReader.Create("http://ServerName/data/books.xml", settings); + // + + // Parse the file. + while (reader.Read()) ; + } +} diff --git a/snippets/csharp/System.Xml/XmlReader/Overview/xml/hireDate.xml b/snippets/csharp/System.Xml/XmlReader/Overview/xml/hireDate.xml new file mode 100644 index 00000000000..e8fedbe6b93 --- /dev/null +++ b/snippets/csharp/System.Xml/XmlReader/Overview/xml/hireDate.xml @@ -0,0 +1,7 @@ + + + 12365 + 2003-01-08 + Accountant + + diff --git a/snippets/csharp/System.Xml/XmlReader/Overview/xml/hireDate.xsd b/snippets/csharp/System.Xml/XmlReader/Overview/xml/hireDate.xsd new file mode 100644 index 00000000000..17aa8f8ae9f --- /dev/null +++ b/snippets/csharp/System.Xml/XmlReader/Overview/xml/hireDate.xsd @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/snippets/visualbasic/System.Xml.Schema/XmlSchemaSet/Overview/project.vbproj b/snippets/visualbasic/System.Xml.Schema/XmlSchemaSet/Overview/project.vbproj new file mode 100644 index 00000000000..fab5eea6264 --- /dev/null +++ b/snippets/visualbasic/System.Xml.Schema/XmlSchemaSet/Overview/project.vbproj @@ -0,0 +1,9 @@ + + + + Library + vb + net10.0 + + + diff --git a/snippets/visualbasic/System.Xml.Schema/XmlSchemaSet/Overview/validschemaset.vb b/snippets/visualbasic/System.Xml.Schema/XmlSchemaSet/Overview/validschemaset.vb new file mode 100644 index 00000000000..e6ffade64b2 --- /dev/null +++ b/snippets/visualbasic/System.Xml.Schema/XmlSchemaSet/Overview/validschemaset.vb @@ -0,0 +1,46 @@ +' +Imports System.Xml +Imports System.Xml.Schema +Imports System.IO + +Public Module Sample + Public Sub Main() + + ' Create the XmlSchemaSet class. + Dim sc as XmlSchemaSet = new XmlSchemaSet() + + ' Add the schema to the collection. + sc.Add("urn:bookstore-schema", "books.xsd") + + ' Set the validation settings. + Dim settings as XmlReaderSettings = new XmlReaderSettings() + settings.ValidationType = ValidationType.Schema + settings.Schemas = sc + AddHandler settings.ValidationEventHandler, AddressOf ValidationCallBack + + ' Create the XmlReader object. + Dim reader as XmlReader = XmlReader.Create("booksSchemaFail.xml", settings) + + ' Parse the file. + While reader.Read() + End While + + End Sub + + ' Display any validation errors. + Private Sub ValidationCallBack(sender as object, e as ValidationEventArgs) + Console.WriteLine($"Validation Error:{vbCrLf} {e.Message}") + Console.WriteLine() + End Sub +End Module +' The example displays output like the following: +' Validation Error: +' The element 'book' in namespace 'urn:bookstore-schema' has invalid child element 'author' +' in namespace 'urn:bookstore-schema'. List of possible elements expected: 'title' in +' namespace 'urn:bookstore-schema'. +' +' Validation Error: +' The element 'author' in namespace 'urn:bookstore-schema' has invalid child element 'name' +' in namespace 'urn:bookstore-schema'. List of possible elements expected: 'first-name' in +' namespace 'urn:bookstore-schema'. +' \ No newline at end of file diff --git a/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/project.vbproj b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/project.vbproj new file mode 100644 index 00000000000..fab5eea6264 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/project.vbproj @@ -0,0 +1,9 @@ + + + + Library + vb + net10.0 + + + diff --git a/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-element.vb b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-element.vb new file mode 100644 index 00000000000..6276901eedd --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-element.vb @@ -0,0 +1,19 @@ +' +Option Strict On +Option Explicit On +Imports System.Xml + +Public Class ElementSample + Public Shared Sub Main() + 'Create the XmlDocument. + Dim doc As New XmlDocument() + doc.LoadXml("" & + "" & + "Pride And Prejudice" & + "") + + 'Display the document element. + Console.WriteLine(doc.DocumentElement.OuterXml) + End Sub +End Class +' diff --git a/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-lastchild.vb b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-lastchild.vb new file mode 100644 index 00000000000..a3a6d3aa465 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-lastchild.vb @@ -0,0 +1,21 @@ +' +Option Explicit On +Option Strict On +Imports System.Xml + +Public Class LastChildSample + Public Shared Sub Main() + + Dim doc As New XmlDocument() + doc.LoadXml("" & + "Pride And Prejudice" & + "19.95" & + "") + + Dim root As XmlNode = doc.FirstChild + + Console.WriteLine("Display the price element...") + Console.WriteLine(root.LastChild.OuterXml) + End Sub +End Class +' diff --git a/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-nextsibling.vb b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-nextsibling.vb new file mode 100644 index 00000000000..be520167005 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-nextsibling.vb @@ -0,0 +1,20 @@ +' +Imports System.Xml + +Public Class NextSiblingSample + Public Shared Sub Main() + + Dim doc As XmlDocument = New XmlDocument() + doc.Load("books.xml") + + Dim currNode As XmlNode = doc.DocumentElement.FirstChild + Console.WriteLine("First book...") + Console.WriteLine(currNode.OuterXml) + + Dim nextNode As XmlNode = currNode.NextSibling + Console.WriteLine(ControlChars.Lf + "Second book...") + Console.WriteLine(nextNode.OuterXml) + + End Sub +End Class +' diff --git a/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-tag.vb b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-tag.vb new file mode 100644 index 00000000000..ebf14792b07 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-tag.vb @@ -0,0 +1,21 @@ +' +Option Explicit On +Option Strict On +Imports System.Xml + +Public Class TagSample + + Public Shared Sub Main() + 'Create the XmlDocument. + Dim doc As New XmlDocument() + doc.Load("books.xml") + + 'Display all the book titles. + Dim elemList As XmlNodeList = doc.GetElementsByTagName("title") + Dim i As Integer + For i = 0 To elemList.Count - 1 + Console.WriteLine(elemList(i).InnerXml) + Next i + End Sub +End Class +' diff --git a/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source2.vb b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source2.vb new file mode 100644 index 00000000000..fc0b2b58c19 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source2.vb @@ -0,0 +1,29 @@ +' +Option Strict +Option Explicit + +Imports System.IO +Imports System.Xml + +Public Class Sample + + Public Shared Sub Main() + + Dim doc As New XmlDocument() + doc.LoadXml("" & _ + "Pride And Prejudice" & _ + "19.95" & _ + "") + + Dim root As XmlNode = doc.FirstChild + + 'Display the contents of the child nodes. + If root.HasChildNodes Then + Dim i As Integer + For i = 0 To root.ChildNodes.Count - 1 + Console.WriteLine(root.ChildNodes(i).InnerText) + Next i + End If + End Sub +End Class +' diff --git a/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source5.vb b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source5.vb new file mode 100644 index 00000000000..eebedcf9bff --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source5.vb @@ -0,0 +1,18 @@ +' +Imports System.Xml + +Public Class Sample5 + Public Shared Sub Main() + Dim doc As XmlDocument = New XmlDocument() + doc.Load("books.xml") + + Dim lastNode As XmlNode = doc.DocumentElement.LastChild + Console.WriteLine("Last book...") + Console.WriteLine(lastNode.OuterXml) + + Dim prevNode As XmlNode = lastNode.PreviousSibling + Console.WriteLine(ControlChars.Lf + "Previous book...") + Console.WriteLine(prevNode.OuterXml) + End Sub +End Class +' diff --git a/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/constants.vb b/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/constants.vb new file mode 100644 index 00000000000..f28a564b8a5 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/constants.vb @@ -0,0 +1,17 @@ +Public Class Constants + + Public Const positionTop As String = "Top" + Public Const positionBottom As String = "Bottom" + Public Const positionAbove As String = "Above selected item" + Public Const positionBelow As String = "Below selected item" + Public Const lengthOfNamespaceDeclaration As Integer = 37 + Public Const booksFileName As String = "booksData.xml" + Public Const Title As String = "Title" + Public Const Genre As String = "Genre" + Public Const PubDate As String = "Publish Year" + Public Const Price As String = "Price" + Public Const ISBN As String = "ISBN" + Public Const Condition As String = "Condition" + Public Const Excludes As String = "Excludes" + +End Class diff --git a/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/project.vbproj b/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/project.vbproj new file mode 100644 index 00000000000..429a73db362 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/project.vbproj @@ -0,0 +1,9 @@ + + + + WinExe + net10.0-windows + true + + + diff --git a/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/source.vb b/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/source.vb new file mode 100644 index 00000000000..1e20179172e --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/source.vb @@ -0,0 +1,29 @@ +' +Imports System.IO +Imports System.Xml + +public class Sample + + public shared sub Main() + + 'Create the XmlDocument. + Dim doc as XmlDocument = new XmlDocument() + doc.Load("booksort.xml") + + Dim book as XmlNode + Dim nodeList as XmlNodeList + Dim root as XmlNode = doc.DocumentElement + + nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']") + + 'Change the price on the books. + for each book in nodeList + book.LastChild.InnerText="15.95" + next + + Console.WriteLine("Display the modified XML document....") + doc.Save(Console.Out) + + end sub +end class + ' diff --git a/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/xmlhelpermethods.vb b/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/xmlhelpermethods.vb new file mode 100644 index 00000000000..d2c4d6733a0 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/xmlhelpermethods.vb @@ -0,0 +1,559 @@ +Imports System.Collections +Imports System.IO +Imports System.Xml +Imports System.Xml.Schema +Imports System.Text + +Public Class XMLHelperMethods + +#Region "Load and Save XML" + '************************************************************************************ + ' + ' Loads XML from a file. If the file is not found, load XML from a string. + ' + '************************************************************************************ + Public Function LoadDocument(ByVal generateXML As Boolean) As XmlDocument + ' + Dim doc As XmlDocument = New XmlDocument + doc.PreserveWhitespace = True + Try + doc.Load("booksData.xml") + Catch ex As System.IO.FileNotFoundException + ' If no file is found, generate some XML. + doc.LoadXml(" " & ControlChars.NewLine & _ + " " & ControlChars.NewLine & _ + " " & ControlChars.NewLine & _ + " Pride And Prejudice " & ControlChars.NewLine & _ + " 24.95 " & ControlChars.NewLine & _ + " " & ControlChars.NewLine & _ + " " & ControlChars.NewLine & _ + " The Handmaid's Tale " & ControlChars.NewLine & _ + " 29.95 " & ControlChars.NewLine & _ + " " & ControlChars.NewLine & _ + "") + End Try + ' + Return doc + End Function + + '************************************************************************************ + ' + ' Helper method that generates an XML string. + ' + '************************************************************************************ + Private Function generateXMLString() As String + Dim xml As String = " " & ControlChars.NewLine & _ + " " & ControlChars.NewLine & _ + " " & ControlChars.NewLine & _ + " Pride And Prejudice " & ControlChars.NewLine & _ + " 24.95 " & ControlChars.NewLine & _ + " " & ControlChars.NewLine & _ + " " & ControlChars.NewLine & _ + " The Handmaid's Tale " & ControlChars.NewLine & _ + " 29.95 " & ControlChars.NewLine & _ + " " & ControlChars.NewLine & _ + " " & ControlChars.NewLine & + " Sense and Sensibility " & ControlChars.NewLine & _ + " 19.95 " & ControlChars.NewLine & _ + " " & ControlChars.NewLine & _ + "" + Return xml + End Function + + '************************************************************************************ + ' + ' Summery: Loads XML from a file. If the file is not found, load XML from a string. + ' + '************************************************************************************ + Public Sub SaveXML(ByVal doc As XmlDocument) + doc.Save(Constants.booksFileName) + End Sub + +#End Region + +#Region "Validate XML against a Schema" + ' + '************************************************************************************ + ' + ' Associate the schema with XML. Then, load the XML and validate it against + ' the schema. + ' + '************************************************************************************ + Public Function LoadDocumentWithSchemaValidation(ByVal generateXML As Boolean, ByVal generateSchema As Boolean) As XmlDocument + Dim reader As XmlReader + Dim settings As XmlReaderSettings = New XmlReaderSettings + ' Helper method to retrieve schema. + Dim schema As XmlSchema = getSchema(generateSchema) + If (schema Is Nothing) Then + Return Nothing + End If + settings.Schemas.Add(schema) + AddHandler settings.ValidationEventHandler, AddressOf settings_ValidationEventHandler + settings.ValidationFlags = (settings.ValidationFlags Or XmlSchemaValidationFlags.ReportValidationWarnings) + settings.ValidationType = ValidationType.Schema + Try + reader = XmlReader.Create("booksData.xml", settings) + Catch ex As System.IO.FileNotFoundException + If generateXML Then + Dim xml As String = generateXMLString() + Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xml) + Dim stream As MemoryStream = New MemoryStream(byteArray) + reader = XmlReader.Create(stream, settings) + Else + Return Nothing + End If + End Try + Dim doc As XmlDocument = New XmlDocument + doc.PreserveWhitespace = True + doc.Load(reader) + reader.Close() + Return doc + End Function + + '************************************************************************************ + ' + ' Helper method that generates an XML Schema. + ' + '************************************************************************************ + Private Function generateXMLSchema() As String + + Dim generatedXmlSchema As String = " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " & _ + " " + + + Return generatedXmlSchema + + End Function + + '************************************************************************************ + ' + ' Helper method that gets a schema + ' + '************************************************************************************ + Private Function getSchema(ByVal generateSchema As Boolean) As XmlSchema + Dim xs As XmlSchemaSet = New XmlSchemaSet + Dim schema As XmlSchema + Try + schema = xs.Add("http://www.contoso.com/books", "booksData.xsd") + Catch ex As System.IO.FileNotFoundException + If generateSchema Then + Dim xmlSchemaString As String = generateXMLSchema() + Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xmlSchemaString) + Dim stream As MemoryStream = New MemoryStream(byteArray) + Dim reader As XmlReader = XmlReader.Create(stream) + schema = xs.Add("http://www.contoso.com/books", reader) + Else + Return Nothing + End If + End Try + Return schema + End Function + + '************************************************************************************ + ' + ' Helper method to validate the XML against the schema. + ' + '************************************************************************************ + Private Sub validateXML(ByVal generateSchema As Boolean, ByVal doc As XmlDocument) + If (doc.Schemas.Count = 0) Then + ' Helper method to retrieve schema. + Dim schema As XmlSchema = getSchema(generateSchema) + doc.Schemas.Add(schema) + End If + ' Use an event handler to validate the XML node against the schema. + doc.Validate(AddressOf settings_ValidationEventHandler) + End Sub + + '************************************************************************************ + ' + ' Event handler that is raised when XML doesn't validate against the schema. + ' + '************************************************************************************ + Private Sub settings_ValidationEventHandler(ByVal sender As Object, ByVal e As System.Xml.Schema.ValidationEventArgs) + If (e.Severity = XmlSeverityType.Warning) Then + System.Windows.Forms.MessageBox.Show(("The following validation warning occurred: " & e.Message)) + ElseIf (e.Severity = XmlSeverityType.Error) Then + System.Windows.Forms.MessageBox.Show(("The following critical validation errors occurred: " & e.Message)) + Dim objectType As Type = sender.GetType + End If + End Sub + ' + +#End Region + +#Region "Find Elements and attributes" + + '************************************************************************************ + ' + ' Search the XML tree for a specific XMLNode element by using an attribute value. + ' Description: Must identify the namespace of the nodes and define a prefix. Also include the + ' prefix in the XPath string. + ' + '************************************************************************************ + ' + Public Function GetBook(ByVal uniqueAttribute As String, ByVal doc As XmlDocument) As XmlNode + Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable) + nsmgr.AddNamespace("bk", "http://www.contoso.com/books") + Dim xPathString As String = ("//bk:books/bk:book[@ISBN='" _ + & (uniqueAttribute & "']")) + Dim xmlNode As XmlNode = doc.DocumentElement.SelectSingleNode(xPathString, nsmgr) + Return xmlNode + End Function + ' + + '************************************************************************************ + ' + ' Get information about a specific book. Pass in an XMLNode that + ' represents the book and populate strings passed in by reference. + ' + '************************************************************************************ + ' + Public Sub GetBookInformation(ByRef title As String, ByRef ISBN As String, ByRef publicationDate As String, ByRef price As String, ByRef genre As String, ByVal book As XmlNode) + Dim bookElement As XmlElement = CType(book, XmlElement) + ' Get the attributes of a book. + Dim attr As XmlAttribute = bookElement.GetAttributeNode("ISBN") + ISBN = attr.InnerXml + attr = bookElement.GetAttributeNode("genre") + genre = attr.InnerXml + attr = bookElement.GetAttributeNode("publicationdate") + publicationDate = attr.InnerXml + ' Get the values of child elements of a book. + title = bookElement("title").InnerText + price = bookElement("price").InnerText + End Sub + ' + + '************************************************************************************ + ' + ' Uses filter criteria collection in the UI to retrieve specific elements and attributes. + ' + '************************************************************************************ + Public Function ApplyFilters(ByVal conditions As ArrayList, ByVal operatorSymbols As ArrayList, ByVal values As ArrayList, ByVal doc As XmlDocument, ByVal matchString As String) As XmlNodeList + Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable) + + nsmgr.AddNamespace("bk", "http://www.contoso.com/books") + Dim xPathQueryString As String = "//bk:books/bk:book[" + Dim xPathQueryEnding As String = "]" + Dim xPathQueryStrings As ArrayList = New ArrayList + Dim booleanOperator As String + If (matchString = "Any") Then + booleanOperator = "or " + Else + booleanOperator = "and " + End If + Dim counter As Integer = 0 + Dim operatorArray() As String = CType(operatorSymbols.ToArray(GetType(System.String)), String()) + Dim valueArray() As String = CType(values.ToArray(GetType(System.String)), String()) + For Each condition As String In conditions + Dim xPathQueryPart As String = "" + Dim operatorSymbol As String = operatorArray(counter) + Dim value As String = valueArray(counter) + If (counter > 0) Then + xPathQueryString = (xPathQueryString & booleanOperator) + End If + counter = (counter + 1) + Select Case (condition) + Case Constants.Title + Select Case (operatorSymbol) + Case "Contains" + xPathQueryPart = ("contains(bk:title,'" _ + & (value & "')")) + Case "Excludes" + xPathQueryPart = ("not(contains(bk:title,'" _ + & (value & "'))")) + Case "=" + xPathQueryPart = ("bk:title='" _ + & (value & "'")) + End Select + Case Constants.ISBN + Select Case (operatorSymbol) + Case "Contains" + xPathQueryPart = ("contains(@ISBN, '" _ + & (value & "')")) + Case "Excludes" + xPathQueryPart = ("not(contains(@ISBN, '" _ + & (value & "'))")) + Case "=" + xPathQueryPart = ("@ISBN='" _ + & (value & "'")) + End Select + Case Constants.PubDate + xPathQueryPart = ("contains(@publicationdate, '" _ + & (value & "')")) + Case Constants.Price + Select Case (operatorSymbol) + Case "=" + xPathQueryPart = ("bk:price='" _ + & (value & "'")) + Case ">" + xPathQueryPart = ("bk:price>'" _ + & (value & "'")) + Case "<" + xPathQueryPart = ("bk:price<'" _ + & (value & "'")) + Case ">=" + xPathQueryPart = ("bk:price>='" _ + & (value & "'")) + Case "<=" + xPathQueryPart = ("bk:price<='" _ + & (value & "'")) + Case "<>" + xPathQueryPart = ("bk:price!='" _ + & (value & "'")) + End Select + Case Constants.Genre + xPathQueryPart = ("@genre='" _ + & (value & "'")) + End Select + xPathQueryString = (xPathQueryString & xPathQueryPart) + Next + xPathQueryString = (xPathQueryString & xPathQueryEnding) + Dim nodeList As XmlNodeList = doc.DocumentElement.SelectNodes(xPathQueryString, nsmgr) + Return nodeList + End Function + +#End Region + +#Region "Add XML elements and attributes" + '************************************************************************************ + ' + ' Add an element to the XML document. + ' This method creates a new book element and saves that element to the + ' XMLDocument object. It addes attributes for the new element and introduces + ' newline characters between elements fora nice readable format. + ' + ' + '************************************************************************************ + ' + Public Function AddNewBook(ByVal genre As String, ByVal ISBN As String, ByVal misc As String, ByVal title As String, ByVal price As String, ByVal doc As XmlDocument) As XmlElement + ' Create a new book element. + Dim bookElement As XmlElement = doc.CreateElement("book", "http://www.contoso.com/books") + + ' Create attributes for book and append them to the book element. + Dim attribute As XmlAttribute = doc.CreateAttribute("genre") + attribute.Value = genre + bookElement.Attributes.Append(attribute) + + attribute = doc.CreateAttribute("ISBN") + attribute.Value = ISBN + bookElement.Attributes.Append(attribute) + + attribute = doc.CreateAttribute("publicationdate") + attribute.Value = misc + bookElement.Attributes.Append(attribute) + + ' Create and append a child element for the title of the book. + Dim titleElement As XmlElement = doc.CreateElement("title") + titleElement.InnerText = title + bookElement.AppendChild(titleElement) + + ' Introduce a newline character so that XML is nicely formatted. + bookElement.InnerXml = bookElement.InnerXml.Replace(titleElement.OuterXml, _ + "\n " & titleElement.OuterXml & " " & ControlChars.NewLine + " ") + ' Create and append a child element for the price of the book. + Dim priceElement As XmlElement = doc.CreateElement("price") + priceElement.InnerText = price + bookElement.AppendChild(priceElement) + + ' Introduce a newline character so that XML is nicely formatted. + bookElement.InnerXml = bookElement.InnerXml.Replace(priceElement.OuterXml, + (priceElement.OuterXml & " " & ControlChars.NewLine & " ")) + Return bookElement + End Function + ' + + '************************************************************************************ + ' + ' Add an element to the XML document at a specific location + ' Takes a string that describes where the user wants the new node + ' to be positioned. The string comes from a series of radio buttons in a UI. + ' this method also accepts the XMLDocument in context. You have to use the + ' this instance because it is the object that was used to generate the + ' selectedBook XMLNode. + ' + '************************************************************************************ + Public Sub InsertBookElement(ByVal bookElement As XmlElement, ByVal position As String, + ByVal selectedBook As XmlNode, ByVal validateNode As Boolean, + ByVal generateSchema As Boolean) + Dim doc As XmlDocument = bookElement.OwnerDocument + Dim stringThatContainsNewline As String = bookElement.OuterXml + + Dim sigWhiteSpace As XmlSignificantWhitespace + + Select Case (position) + + Case Constants.positionTop + ' Add newline characters and spaces to make XML more readable. + sigWhiteSpace = doc.CreateSignificantWhitespace(ControlChars.NewLine & " ") + doc.DocumentElement.InsertBefore(sigWhiteSpace, doc.DocumentElement.FirstChild) + doc.DocumentElement.InsertAfter(bookElement, doc.DocumentElement.FirstChild) + + Case Constants.positionBottom + ' Add newline characters to make XML more readable. + Dim whitespace As XmlWhitespace = doc.CreateWhitespace(" ") + Dim appendedNode As XmlNode = doc.DocumentElement.AppendChild(bookElement) + doc.DocumentElement.InsertBefore(whitespace, appendedNode) + sigWhiteSpace = doc.CreateSignificantWhitespace(ControlChars.NewLine) + doc.DocumentElement.InsertAfter(sigWhiteSpace, appendedNode) + + Case Constants.positionAbove + ' Add newline characters to make XML more readable. + Dim currNode As XmlNode = doc.DocumentElement.InsertBefore(bookElement, selectedBook) + sigWhiteSpace = doc.CreateSignificantWhitespace(ControlChars.NewLine & " ") + doc.DocumentElement.InsertAfter(sigWhiteSpace, currNode) + + Case Constants.positionBelow + ' Add newline characters to make XML more readable. + sigWhiteSpace = doc.CreateSignificantWhitespace(ControlChars.NewLine & " ") + Dim whiteSpaceNode As XmlNode = doc.DocumentElement.InsertAfter(sigWhiteSpace, selectedBook) + doc.DocumentElement.InsertAfter(bookElement, whiteSpaceNode) + + Case Else + doc.DocumentElement.AppendChild(bookElement) + + End Select + + If validateNode Then + validateXML(generateSchema, doc) + End If + End Sub +#End Region + +#Region "Edit XML elements and attributes" + '************************************************************************************ + ' + ' Edit an XML element + ' + ' + '************************************************************************************ + ' + Public Sub editBook(ByVal title As String, ByVal ISBN As String, + ByVal publicationDate As String, ByVal genre As String, + ByVal price As String, ByVal book As XmlNode, ByVal validateNode As Boolean, + ByVal generateSchema As Boolean) + + Dim bookElement As XmlElement = CType(book, XmlElement) + + ' Get the attributes of a book. + bookElement.SetAttribute("ISBN", ISBN) + bookElement.SetAttribute("genre", genre) + bookElement.SetAttribute("publicationdate", publicationDate) + + ' Get the values of child elements of a book. + bookElement("title").InnerText = title + bookElement("price").InnerText = price + If validateNode Then + validateXML(generateSchema, bookElement.OwnerDocument) + End If + + End Sub + ' + +#End Region + +#Region "Remove elements" + '************************************************************************************ + ' + ' Summary: Delete a book node from the XMLDocument. + ' + ' + '************************************************************************************ + ' + Public Sub deleteBook(ByVal book As XmlNode) + + Dim prevNode As XmlNode = book.PreviousSibling + book.OwnerDocument.DocumentElement.RemoveChild(book) + + If ((prevNode.NodeType = XmlNodeType.Whitespace) _ + OrElse (prevNode.NodeType = XmlNodeType.SignificantWhitespace)) Then + prevNode.OwnerDocument.DocumentElement.RemoveChild(prevNode) + + End If + End Sub + ' + +#End Region + +#Region "Position elements" +' + '************************************************************************************ + ' + ' Summary: Move elements up in the XML. + ' + ' + '************************************************************************************ + Public Sub MoveElementUp(ByVal book As XmlNode) + Dim previousNode As XmlNode = book.PreviousSibling + + While ((Not (previousNode) Is Nothing) _ + AndAlso (previousNode.NodeType <> XmlNodeType.Element)) + previousNode = previousNode.PreviousSibling + + End While + If (Not (previousNode) Is Nothing) Then + Dim newLineNode As XmlNode = book.NextSibling + book.OwnerDocument.DocumentElement.RemoveChild(book) + + If ((newLineNode.NodeType = XmlNodeType.Whitespace) _ + Or (newLineNode.NodeType = XmlNodeType.SignificantWhitespace)) Then + newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode) + End If + + InsertBookElement(CType(book, XmlElement), Constants.positionAbove, + previousNode, False, False) + End If + End Sub + + '************************************************************************************ + ' + ' Summary: Move elements down in the XML. + ' + ' + '************************************************************************************ + Public Sub MoveElementDown(ByVal book As XmlNode) + ' Walk backwards until we find an element - ignore text nodes + Dim NextNode As XmlNode = book.NextSibling + + While ((Not (NextNode) Is Nothing) _ + AndAlso (NextNode.NodeType <> XmlNodeType.Element)) + NextNode = NextNode.NextSibling + + End While + + If (Not (NextNode) Is Nothing) Then + Dim newLineNode As XmlNode = book.PreviousSibling + book.OwnerDocument.DocumentElement.RemoveChild(book) + + If ((newLineNode.NodeType = XmlNodeType.Whitespace) _ + Or (newLineNode.NodeType = XmlNodeType.SignificantWhitespace)) Then + newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode) + End If + + InsertBookElement(CType(book, XmlElement), Constants.positionBelow, + NextNode, False, False) + End If + End Sub +' +#End Region + +End Class diff --git a/snippets/visualbasic/System.Xml/XmlReader/Create/Project.vbproj b/snippets/visualbasic/System.Xml/XmlReader/Create/Project.vbproj new file mode 100644 index 00000000000..874c98f3477 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlReader/Create/Project.vbproj @@ -0,0 +1,8 @@ + + + + Library + net10.0 + + + diff --git a/snippets/visualbasic/System.Xml/XmlReader/Create/XmlReader_Create.vb b/snippets/visualbasic/System.Xml/XmlReader/Create/XmlReader_Create.vb new file mode 100644 index 00000000000..26785a03e26 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlReader/Create/XmlReader_Create.vb @@ -0,0 +1,202 @@ +Imports System.Text +Imports System.IO +Imports System.Xml +Imports System.Xml.Schema +Imports System.Net + + +Class XmlReaderSettings_Examples + + Shared Sub Main() + + End Sub + + ' + Shared Sub String_Fragment() + ' + Dim xmlFrag As String = "hammer " & _ + "paint" & _ + "saw" + + ' Create the XmlNamespaceManager. + Dim nt As New NameTable() + Dim nsmgr As New XmlNamespaceManager(nt) + nsmgr.AddNamespace("rk", "urn:store-items") + + ' Create the XmlParserContext. + Dim context As New XmlParserContext(Nothing, nsmgr, Nothing, XmlSpace.None) + + ' Create the reader. + Dim settings As New XmlReaderSettings() + settings.ConformanceLevel = ConformanceLevel.Fragment + Dim reader As XmlReader = XmlReader.Create(New StringReader(xmlFrag), settings, context) + ' + End Sub + + + ' Load URI with XmlResolver + Shared Sub Settings_Resolver() + Dim UserName As String = "username" + Dim SecurelyStoredPassword As String = "psswd" + Dim Domain As String = "domain" + + ' + ' Create an XmlUrlResolver with the credentials necessary to access the Web server. + Dim resolver As New XmlUrlResolver() + Dim myCred As System.Net.NetworkCredential + myCred = New System.Net.NetworkCredential(UserName, SecurelyStoredPassword, Domain) + resolver.Credentials = myCred + + Dim settings As New XmlReaderSettings() + settings.XmlResolver = resolver + + ' Create the reader. + Dim reader As XmlReader = XmlReader.Create("http://serverName/data/books.xml", settings) + ' + End Sub + + + ' DTD Validation + Shared Sub Settings_ProhibitDtd() + ' + ' Set the validation settings. + Dim settings As New XmlReaderSettings() + settings.DtdProcessing = DtdProcessing.Parse + settings.ValidationType = ValidationType.DTD + AddHandler settings.ValidationEventHandler, AddressOf ValidationCallBack + + ' Create the XmlReader object. + Dim reader As XmlReader = XmlReader.Create("itemDTD.xml", settings) + + ' Parse the file. + While reader.Read() + End While + ' + End Sub + + + ' + ' Display any validation errors. + Private Shared Sub ValidationCallBack(ByVal sender As Object, ByVal e As ValidationEventArgs) + Console.WriteLine("Validation Error: {0}", e.Message) + + End Sub + + ' + + ' Wrapped Reader + Shared Sub WrappedReader_Settings() + ' + ' Create the XmlNodeReader object. + Dim doc As New XmlDocument() + doc.Load("books.xml") + Dim nodeReader As New XmlNodeReader(doc) + + ' Set the validation settings. + Dim settings As New XmlReaderSettings() + settings.ValidationType = ValidationType.Schema + settings.Schemas.Add("urn:bookstore-schema", "books.xsd") + AddHandler settings.ValidationEventHandler, AddressOf ValidationCallBack + + ' Create a validating reader that wraps the XmlNodeReader object. + Dim reader As XmlReader = XmlReader.Create(nodeReader, settings) + ' Parse the XML file. + While reader.Read() + End While + ' + End Sub + + + Shared Sub URI() + ' + ' Create the XmlReader object. + Dim reader As XmlReader = XmlReader.Create("books.xml") + ' + End Sub + + + Shared Sub XML_String() + ' + Dim xmlData As String = "" & _ + "5.95" & _ + "" + + ' Create the XmlReader object. + Dim reader As XmlReader = XmlReader.Create(New StringReader(xmlData)) + ' + End Sub + + + Shared Sub FileStream() + ' + Dim fs As New FileStream("C:\data\books.xml", FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read) + + ' Create the XmlReader object. + Dim reader As XmlReader = XmlReader.Create(fs) + + End Sub + ' + + Shared Sub FileStream_Settings() + ' + Dim fs As New FileStream("C:\data\books.xml", FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read) + + Dim resolver As New XmlUrlResolver() + resolver.Credentials = CredentialCache.DefaultCredentials + Dim settings As New XmlReaderSettings() + settings.XmlResolver = resolver + + ' Create the XmlReader object. + Dim reader As XmlReader = XmlReader.Create(fs, settings) + ' + End Sub + + ' Secure Resolver + Shared Sub Settings_SecureResolver() + ' +' Create an XmlSecureResolver with default credentials. +Dim myResolver As New XmlSecureResolver(New XmlUrlResolver(), "http://serverName/data/") +myResolver.Credentials = CredentialCache.DefaultCredentials + +Dim settings As New XmlReaderSettings() +settings.XmlResolver = myResolver + +' Create the reader. +Dim reader As XmlReader = XmlReader.Create("http://serverName/data/books.xml", settings) + + ' + End Sub + + ' + Shared Sub GeneralSettings() + ' +Dim settings As New XmlReaderSettings() +settings.ConformanceLevel = ConformanceLevel.Fragment +settings.IgnoreWhitespace = true +settings.IgnoreComments = true +Dim reader As XmlReader = XmlReader.Create("books.xml", settings) + ' + End Sub + + Shared Sub ChainReaders() + ' +Dim settings As New XmlReaderSettings() +settings.ValidationType = ValidationType.DTD +Dim inner As XmlReader = XmlReader.Create("book.xml", settings) ' DTD Validation +settings.Schemas.Add("urn:book-schema", "book.xsd") +settings.ValidationType = ValidationType.Schema +Dim outer As XmlReader = XmlReader.Create(inner, settings) ' XML Schema Validation + ' + End Sub + + Shared Sub WrapTextReader() + ' +Dim txtReader As XmlTextReader = New XmlTextReader("bookOrder.xml") +Dim settings As New XmlReaderSettings() +settings.Schemas.Add("urn:po-schema", "PO.xsd") +settings.ValidationType = ValidationType.Schema +Dim reader As XmlReader = XmlReader.Create(txtReader, settings) + ' + End Sub + +End Class diff --git a/snippets/visualbasic/System.Xml/XmlReader/Create/factory_rdr_cctor2.vb b/snippets/visualbasic/System.Xml/XmlReader/Create/factory_rdr_cctor2.vb new file mode 100644 index 00000000000..efff7cb8710 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlReader/Create/factory_rdr_cctor2.vb @@ -0,0 +1,35 @@ +Imports System.Xml +Imports System.Xml.Schema +Imports System.IO + +public class Sample + + public shared sub Main() + + ' + ' Set the reader settings. + Dim settings as XmlReaderSettings = new XmlReaderSettings() + settings.IgnoreComments = true + settings.IgnoreProcessingInstructions = true + settings.IgnoreWhitespace = true + ' + + ' + ' Create a resolver with default credentials. + Dim resolver as XmlUrlResolver = new XmlUrlResolver() + resolver.Credentials = System.Net.CredentialCache.DefaultCredentials + + ' Set the reader settings object to use the resolver. + settings.XmlResolver = resolver + + ' Create the XmlReader object. + Dim reader as XmlReader = XmlReader.Create("http://ServerName/data/books.xml", settings) + ' + + ' Parse the file. + while reader.Read() + end while + end sub + + +end class diff --git a/snippets/visualbasic/System.Xml/XmlReader/Overview/Project.vbproj b/snippets/visualbasic/System.Xml/XmlReader/Overview/Project.vbproj new file mode 100644 index 00000000000..874c98f3477 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlReader/Overview/Project.vbproj @@ -0,0 +1,8 @@ + + + + Library + net10.0 + + + diff --git a/snippets/visualbasic/System.Xml/XmlReader/Overview/readElementContentAs.vb b/snippets/visualbasic/System.Xml/XmlReader/Overview/readElementContentAs.vb new file mode 100644 index 00000000000..29dbfd0f6a7 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlReader/Overview/readElementContentAs.vb @@ -0,0 +1,148 @@ +Imports System.Text +Imports System.IO +Imports System.Xml + +Class Read_Typed_Element + + + Shared Sub Main() + + + ReadElementContentAsString_1() + ReadElementContentAsString_2() + ReadElementContentAsLong_1() + ReadElementContentAsDateTime_1() + ReadElementContentAs_1() + ReadElementContentAsObject() + ReadElementContentAsDouble_1() + + End Sub + + + + Public Shared Sub ReadElementContentAsString_1() + ' + Using reader As XmlReader = XmlReader.Create("dataFile.xml") + reader.ReadToFollowing("stringValue") + Console.WriteLine(reader.ReadElementContentAsString()) + End Using + ' + End Sub + + + Public Shared Sub ReadElementContentAsString_2() + ' + Using reader As XmlReader = XmlReader.Create("dataFile.xml") + reader.ReadToFollowing("stringValue") + Console.WriteLine(reader.ReadElementContentAsString("stringValue", "")) + End Using + ' + End Sub + + + Public Shared Sub ReadElementContentAsLong_1() + ' + Using reader As XmlReader = XmlReader.Create("dataFile.xml") + reader.ReadToFollowing("longValue") + Dim number As Long = reader.ReadElementContentAsLong() + ' Do some processing with the number object. + End Using + ' + End Sub + + + Public Shared Sub ReadElementContentAsDateTime_1() + ' + Using reader As XmlReader = XmlReader.Create("dataFile.xml") + reader.ReadToFollowing("date") + Dim [date] As DateTime = reader.ReadElementContentAsDateTime() + + ' If the current culture is "en-US", + ' this writes "Wednesday, January 8, 2003". + Console.WriteLine([date].ToLongDateString()) + End Using + ' + End Sub + + + Public Shared Sub ReadElementContentAs_1() + ' + Using reader As XmlReader = XmlReader.Create("dataFile.xml") + reader.ReadToFollowing("date") + Dim [date] As DateTime = CType(reader.ReadElementContentAs(GetType(System.DateTime), Nothing), DateTime) + + ' If the current culture is "en-US", + ' this writes "Wednesday, January 8, 2003". + Console.WriteLine([date].ToLongDateString()) + End Using + ' + End Sub + + + Public Shared Sub ReadElementContentAsObject() + ' + ' Create a validating reader. + Dim settings As New XmlReaderSettings() + settings.ValidationType = ValidationType.Schema + settings.Schemas.Add("urn:items", "item.xsd") + Dim reader As XmlReader = XmlReader.Create("item.xml", settings) + + ' Get the CLR type of the price element. + reader.ReadToFollowing("price") + Console.WriteLine(reader.ValueType) + + ' Return the value of the price element as Decimal object. + Dim price As [Decimal] = CType(reader.ReadElementContentAsObject(), [Decimal]) + + ' Add 2.50 to the price. + price = [Decimal].Add(price, 2.5D) + + ' + End Sub + + + Public Shared Sub ReadElementContentAsDouble_1() + ' + Using reader As XmlReader = XmlReader.Create("dataFile.xml") + reader.ReadToFollowing("double") + Dim number As [Double] = reader.ReadElementContentAsDouble() + ' Do some processing with the number object. + End Using + ' + End Sub + +Public Shared Sub ReadTypedData1() +' +' Create a validating XmlReader object. The schema +' provides the necessary type information. +Dim settings As XmlReaderSettings = New XmlReaderSettings() +settings.ValidationType = ValidationType.Schema +settings.Schemas.Add("urn:empl-hire", "hireDate.xsd") +Using reader As XmlReader = XmlReader.Create("hireDate.xml", settings) + ' Move to the hire-date element. + reader.MoveToContent() + reader.ReadToDescendant("hire-date") + + ' Return the hire-date as a DateTime object. + Dim hireDate As DateTime = reader.ReadElementContentAsDateTime() + Console.WriteLine("Six Month Review Date: {0}", hireDate.AddMonths(6)) +End Using + ' +End Sub + +Public Shared Sub ReadTypedData2() +' +' Create an XmlReader object. +Using reader As XmlReader = XmlReader.Create("hireDate_1.xml") + ' Move to the hire-date element. + reader.MoveToContent() + reader.ReadToDescendant("hire-date") + + ' Return the hire-date as a DateTime object. + Dim hireDate As DateTime = reader.ReadElementContentAsDateTime() + Console.WriteLine("Six Month Review Date: {0}", hireDate.AddMonths(6)) +End Using + ' +End Sub + +End Class diff --git a/snippets/visualbasic/System.Xml/XmlReader/Overview/xmlreader_basic.vb b/snippets/visualbasic/System.Xml/XmlReader/Overview/xmlreader_basic.vb new file mode 100644 index 00000000000..002af406050 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlReader/Overview/xmlreader_basic.vb @@ -0,0 +1,353 @@ +Imports System.Text +Imports System.IO +Imports System.Xml + + +Class XmlReader_Samples + + + Shared Sub Main() + + End Sub + + +Shared Sub AttributeCount() +Dim reader As XmlReader = XmlReader.Create("books.xml") +reader.ReadToDescendant("book") +' +' Display all attributes. +If reader.HasAttributes Then + Console.WriteLine("Attributes of <" + reader.Name + ">") + Dim i As Integer + For i = 0 To (reader.AttributeCount - 1) + Console.WriteLine(" {0}", reader(i)) + Next i + ' Move the reader back to the element node. + reader.MoveToElement() +End If +' +End Sub + +'============================== +' +Shared Sub GetAttribute1() +Dim reader As XmlReader = XmlReader.Create("books.xml") +' +reader.ReadToFollowing("book") +Dim isbn As String = reader.GetAttribute(2) + ' +End Sub + +'==============================// +' +Shared Sub GetAttribute2() +Dim reader As XmlReader = XmlReader.Create("books.xml") +' +reader.ReadToFollowing("book") +Dim isbn As String = reader.GetAttribute("ISBN") +Console.WriteLine("The ISBN value: " + isbn) +' +End Sub + +'==============================// +' +Shared Sub MoveToAttribute1() +Dim reader As XmlReader = XmlReader.Create("books.xml") +reader.ReadToFollowing("book") +' +If reader.HasAttributes Then + Console.WriteLine("Attributes of <" + reader.Name + ">") + Dim i As Integer + For i = 0 To reader.AttributeCount - 1 + reader.MoveToAttribute(i) + Console.Write(" {0}={1}", reader.Name, reader.Value) + Next i + reader.MoveToElement() 'Moves the reader back to the element node. +End If +' +End Sub + +'==============================// +' +Shared Sub MoveToFirstAttribute() +Dim reader As XmlReader = XmlReader.Create("books.xml") +' +reader.ReadToFollowing("book") +reader.MoveToFirstAttribute() +Dim genre As String = reader.Value +Console.WriteLine("The genre value: " + genre) +' +End Sub + +'==============================// +' +Shared Sub MoveToNextAttribute() +Dim reader As XmlReader = XmlReader.Create("books.xml") +reader.ReadToFollowing("book") +' +If reader.HasAttributes Then + Console.WriteLine("Attributes of <" + reader.Name + ">") + While reader.MoveToNextAttribute() + Console.WriteLine(" {0}={1}", reader.Name, reader.Value) + End While + ' Move the reader back to the element node. + reader.MoveToElement() +End If +' +End Sub + + +'==============================// +' +Shared Sub Item() +Dim reader As XmlReader = XmlReader.Create("books.xml") +' +reader.ReadToDescendant("book") +Dim isbn As String = reader("ISBN") +Console.WriteLine("The ISBN value: " + isbn) +' +End Sub + + +'==============================// +' +Shared Sub Node_Value() +' +Dim settings As New XmlReaderSettings() +settings.DtdProcessing = DtdProcessing.Parse +Dim reader As XmlReader = XmlReader.Create("items.xml", settings) +reader.MoveToContent() +' Parse the file and display each of the nodes. +While reader.Read() + Select Case reader.NodeType + Case XmlNodeType.Element + Console.Write("<{0}>", reader.Name) + Case XmlNodeType.Text + Console.Write(reader.Value) + Case XmlNodeType.CDATA + Console.Write("", reader.Value) + Case XmlNodeType.ProcessingInstruction + Console.Write("", reader.Name, reader.Value) + Case XmlNodeType.Comment + Console.Write("", reader.Value) + Case XmlNodeType.XmlDeclaration + Console.Write("") + Case XmlNodeType.Document + Case XmlNodeType.DocumentType + Console.Write("", reader.Name) + End Select +End While +' +End Sub + + +'==============================// +' +Shared Sub NamespaceURI() +' +Dim reader As XmlReader = XmlReader.Create("book2.xml") + +' Parse the file. If they exist, display the prefix and +' namespace URI of each node. +While reader.Read() + If reader.IsStartElement() Then + If reader.Prefix = String.Empty Then + Console.WriteLine("<{0}>", reader.LocalName) + Else + Console.Write("<{0}:{1}>", reader.Prefix, reader.LocalName) + Console.WriteLine(" The namespace URI is " + reader.NamespaceURI) + End If + End If +End While +reader.Close() +' +End Sub + + +'============================== +' +Shared Sub IsStartElement() +Dim reader As XmlReader = XmlReader.Create("elems.xml") +' +While reader.Read() + If reader.IsStartElement() Then + If reader.IsEmptyElement Then + Console.WriteLine("<{0}/>", reader.Name) + Else + Console.Write("<{0}> ", reader.Name) + reader.Read() ' Read the start tag. + If reader.IsStartElement() Then ' Handle nested elements. + Console.Write(vbCr + vbLf + "<{0}>", reader.Name) + End If + Console.WriteLine(reader.ReadString()) 'Read the text content of the element. + End If + End If +End While +' +End Sub + + +'============================== +' +Shared Sub ReadEndElement() +' +Using reader As XmlReader = XmlReader.Create("book3.xml") + ' Parse the XML document. ReadString is used to + ' read the text content of the elements. + reader.Read() + reader.ReadStartElement("book") + reader.ReadStartElement("title") + Console.Write("The content of the title element: ") + Console.WriteLine(reader.ReadString()) + reader.ReadEndElement() + reader.ReadStartElement("price") + Console.Write("The content of the price element: ") + Console.WriteLine(reader.ReadString()) + reader.ReadEndElement() + reader.ReadEndElement() +End Using +' +End Sub + +'============================== +' +Shared Sub ReadInnerXml() +' +' Load the file and ignore all white space. +Dim settings As New XmlReaderSettings() +settings.IgnoreWhitespace = True +Using reader As XmlReader = XmlReader.Create("2books.xml") + + ' Moves the reader to the root element. + reader.MoveToContent() + + ' Moves to book node. + reader.Read() + + ' Note that ReadInnerXml only returns the markup of the node's children + ' so the book's attributes are not returned. + Console.WriteLine("Read the first book using ReadInnerXml...") + Console.WriteLine(reader.ReadInnerXml()) + + ' ReadOuterXml returns the markup for the current node and its children + ' so the book's attributes are also returned. + Console.WriteLine("Read the second book using ReadOuterXml...") + Console.WriteLine(reader.ReadOuterXml()) + +End Using +' +End Sub + + +'============================== +' +Shared Sub ReadSubtree() +' +Dim settings As New XmlReaderSettings() +settings.IgnoreWhitespace = True +Using reader As XmlReader = XmlReader.Create("books.xml", settings) + + ' Position the reader on the second book node. + reader.ReadToFollowing("Book") + reader.Skip() + + ' Create another reader that contains just the second book node. + Dim inner As XmlReader = reader.ReadSubtree() + + inner.ReadToDescendant("Title") + Console.WriteLine(inner.Name) + + ' Do additional processing on the inner reader. After you + ' are done, call Close on the inner reader and + ' continue processing using the original reader. + inner.Close() + +End Using +' +End Sub + + +'============================== +' +Shared Sub ReadtoDescendant() +' +Using reader As XmlReader = XmlReader.Create("2books.xml") + + ' Move the reader to the second book node. + reader.MoveToContent() + reader.ReadToDescendant("book") + reader.Skip() 'Skip the first book. + ' Parse the file starting with the second book node. + Do + Select Case reader.NodeType + Case XmlNodeType.Element + Console.Write("<{0}", reader.Name) + While reader.MoveToNextAttribute() + Console.Write(" {0}='{1}'", reader.Name, reader.Value) + End While + Console.Write(">") + Case XmlNodeType.Text + Console.Write(reader.Value) + Case XmlNodeType.EndElement + Console.Write("", reader.Name) + End Select + Loop While reader.Read() + +End Using +' +End Sub + + +'============================== +' +Shared Sub ReadToFollowing() +' +Using reader As XmlReader = XmlReader.Create("books.xml") + reader.ReadToFollowing("book") + Do + Console.WriteLine("ISBN: {0}", reader.GetAttribute("ISBN")) + Loop While reader.ReadToNextSibling("book") +End Using +' +End Sub + + +'============================== +' +Shared Sub HasValue() +' +Dim settings As New XmlReaderSettings() +settings.IgnoreWhitespace = True +Using reader As XmlReader = XmlReader.Create("book1.xml", settings) + ' Parse the file and display each node. + While reader.Read() + If reader.HasValue Then + Console.WriteLine("({0}) {1}={2}", reader.NodeType, reader.Name, reader.Value) + Else + Console.WriteLine("({0}) {1}", reader.NodeType, reader.Name) + End If + End While +End Using +' +End Sub + +'============================== +' +Shared Sub IsStartElement_2() +Using reader As XmlReader = XmlReader.Create("books.xml") +' + ' Parse the file and display each price node. + While reader.Read() + If reader.IsStartElement("price") Then + Console.WriteLine(reader.ReadInnerXml()) + End If + End While +' +End Using +End Sub + +End Class diff --git a/snippets/visualbasic/System.Xml/XmlResolver/Overview/Project.vbproj b/snippets/visualbasic/System.Xml/XmlResolver/Overview/Project.vbproj new file mode 100644 index 00000000000..874c98f3477 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlResolver/Overview/Project.vbproj @@ -0,0 +1,8 @@ + + + + Library + net10.0 + + + diff --git a/snippets/visualbasic/System.Xml/XmlResolver/Overview/Xslt_Load_v2.vb b/snippets/visualbasic/System.Xml/XmlResolver/Overview/Xslt_Load_v2.vb new file mode 100644 index 00000000000..5fe7727d2f4 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlResolver/Overview/Xslt_Load_v2.vb @@ -0,0 +1,203 @@ +Imports System.Text +Imports System.IO +Imports System.Xml +Imports System.Xml.Xsl +Imports System.Xml.XPath +Imports System.Net + +Class XslCompiledTransformLoad + + Shared Sub Main() + + End Sub + +' Load with XPathDocument. +Shared Sub XslCompiledTransform_Load1() +' +Dim xslt As New XslCompiledTransform() +xslt.Load(New XPathDocument("http://serverName/data/xsl/sort.xsl")) +' +End Sub + + +'==============================// +' Load URI with XmlResolver +Shared Sub XslCompiledTransform_Load2() +' +' Create the XslCompiledTransform object. +Dim xslt As New XslCompiledTransform() + +' Create a resolver and set the credentials to use. +Dim resolver As New XmlSecureResolver(New XmlUrlResolver(), "http://serverName/data/") +resolver.Credentials = CredentialCache.DefaultCredentials + +' Load the style sheet. +xslt.Load("http://serverName/data/xsl/sort.xsl", Nothing, resolver) +' +End Sub + +'==============================// +' Load reader with resolver & settings +Shared Sub XslCompiledTransform_Load3() +' +' Create the XslCompiledTransform object. +Dim xslt As New XslCompiledTransform() + +' Create a resolver and set the credentials to use. +Dim resolver As New XmlSecureResolver(New XmlUrlResolver(), "http://serverName/data/") +resolver.Credentials = CredentialCache.DefaultCredentials + +Dim reader As XmlReader = XmlReader.Create("http://serverName/data/xsl/sort.xsl") + +' Create the XsltSettings object with script enabled. +Dim settings As New XsltSettings(False, True) + +' Load the style sheet. +xslt.Load(reader, settings, resolver) +' +End Sub + +'==============================// +' Load with XPathDocument and credentials +Shared Sub XslCompiledTransform_Load4() + + Dim UserName As String = "username" + Dim SecurelyStoredPassword As String = "psswd" + Dim Domain As String = "domain" + +' +' Create a resolver and specify the necessary credentials. +Dim resolver As New XmlUrlResolver() +Dim myCred As System.Net.NetworkCredential +myCred = New System.Net.NetworkCredential(UserName, SecurelyStoredPassword, Domain) +resolver.Credentials = myCred + +' Load the style sheet. +Dim xslt As New XslCompiledTransform() +xslt.Load(New XPathDocument("http://serverName/data/xsl/sort.xsl"), XsltSettings.Default, resolver) +' +End Sub + +'==============================// +' Load with XmlReader +Shared Sub XslCompiledTransform_Load5() +' +' Create a reader that contains the style sheet. +Dim reader As XmlReader = XmlReader.Create("titles.xsl") +reader.ReadToDescendant("xsl:stylesheet") + +' Load the style sheet. +Dim xslt As New XslCompiledTransform() +xslt.Load(reader) +' +End Sub + +'==============================// +' Load with script enabled. +Shared Sub XslCompiledTransform_Load6() +' +' Create the XsltSettings object with script enabled. +Dim settings As New XsltSettings(False, True) + +' Create the XslCompiledTransform object and load the style sheet. +Dim xslt As New XslCompiledTransform() +xslt.Load("sort.xsl", settings, New XmlUrlResolver()) +' +End Sub + +'==============================// +' Load with default XSLT settings. +Shared Sub XslCompiledTransform_Load7() +' +' Create the XslCompiledTransform object and load the style sheet. +Dim xslt As New XslCompiledTransform() +xslt.Load("sort.xsl", XsltSettings.Default, New XmlUrlResolver()) +' +End Sub + +'==============================// +' Load with trusted XSLT settings. +Shared Sub XslCompiledTransform_Load8() + + Dim UserName As String = "username" + Dim SecurelyStoredPassword As String = "psswd" + Dim Domain As String = "domain" + +' +' Create a resolver and specify the necessary credentials. +Dim resolver As New XmlSecureResolver(New XmlUrlResolver(), "http://serverName/data/") +Dim myCred As System.Net.NetworkCredential +myCred = New System.Net.NetworkCredential(UserName, SecurelyStoredPassword, Domain) +resolver.Credentials = myCred + +' Create the XslCompiledTransform object and load the style sheet. +Dim xslt As New XslCompiledTransform() +xslt.Load("http://serverName/data/script.xsl", XsltSettings.TrustedXslt, resolver) +' +End Sub + +'==============================// +' Load with script enabled. +Shared Sub XslCompiledTransform_Load9() +' +' Create the XsltSettings object with script enabled. +Dim settings As New XsltSettings() +settings.EnableScript = True + +' Create a resolver that will be used to resolve the style sheet. +Dim resolver As New XmlSecureResolver(New XmlUrlResolver(), "http://serverName/data/") + +' Create the XslCompiledTransform object and load the style sheet. +Dim xslt As New XslCompiledTransform() +xslt.Load("http://serverName/data/sort.xsl", settings, resolver) +' +End Sub + +'==============================// +' +Shared Sub XslCompiledTransform_Debug() +' +' Enable XSLT debugging. +Dim xslt As New XslCompiledTransform(true) + +' Load the style sheet. +xslt.Load("output.xsl") + +' Create the writer. +Dim settings As New XmlWriterSettings() +settings.Indent=true +Dim writer As XmlWriter = XmlWriter.Create("output.xml", settings) + +' Execute the transformation. +xslt.Transform("books.xml", writer) +writer.Close() +' +End Sub + +'==============================// +' Load w/ cache +Shared Sub Cache() + + Dim UserName As String = "username" + Dim SecurelyStoredPassword As String = "psswd" + Dim Domain As String = "domain" + +' +' Create the credentials. +Dim myCred As NetworkCredential = New NetworkCredential(UserName,SecurelyStoredPassword,Domain) +Dim myCache As CredentialCache = New CredentialCache() +myCache.Add(new Uri("http://www.contoso.com/"), "Basic", myCred) +myCache.Add(new Uri("http://app.contoso.com/"), "Basic", myCred) + +' Set the credentials on the XmlUrlResolver object. +Dim resolver As XmlUrlResolver = New XmlUrlResolver() +resolver.Credentials = myCache + +' Compile the style sheet. +Dim xslt As XslCompiledTransform = New XslCompiledTransform() +xslt.Load("http://serverName/data/xsl/order.xsl", XsltSettings.Default, resolver) + +' +End Sub + +End Class \ No newline at end of file diff --git a/snippets/visualbasic/System.Xml/XmlResolver/Overview/factory_rdr_cctor2.vb b/snippets/visualbasic/System.Xml/XmlResolver/Overview/factory_rdr_cctor2.vb new file mode 100644 index 00000000000..efff7cb8710 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlResolver/Overview/factory_rdr_cctor2.vb @@ -0,0 +1,35 @@ +Imports System.Xml +Imports System.Xml.Schema +Imports System.IO + +public class Sample + + public shared sub Main() + + ' + ' Set the reader settings. + Dim settings as XmlReaderSettings = new XmlReaderSettings() + settings.IgnoreComments = true + settings.IgnoreProcessingInstructions = true + settings.IgnoreWhitespace = true + ' + + ' + ' Create a resolver with default credentials. + Dim resolver as XmlUrlResolver = new XmlUrlResolver() + resolver.Credentials = System.Net.CredentialCache.DefaultCredentials + + ' Set the reader settings object to use the resolver. + settings.XmlResolver = resolver + + ' Create the XmlReader object. + Dim reader as XmlReader = XmlReader.Create("http://ServerName/data/books.xml", settings) + ' + + ' Parse the file. + while reader.Read() + end while + end sub + + +end class diff --git a/snippets/visualbasic/System.Xml/XmlSecureResolver/Overview/Project.vbproj b/snippets/visualbasic/System.Xml/XmlSecureResolver/Overview/Project.vbproj new file mode 100644 index 00000000000..e7ab3e8988d --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlSecureResolver/Overview/Project.vbproj @@ -0,0 +1,8 @@ + + + + Library + net48 + + + diff --git a/snippets/visualbasic/System.Xml/XmlSecureResolver/Overview/XmlSecureResolver_ex.vb b/snippets/visualbasic/System.Xml/XmlSecureResolver/Overview/XmlSecureResolver_ex.vb new file mode 100644 index 00000000000..a55bc54a60e --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlSecureResolver/Overview/XmlSecureResolver_ex.vb @@ -0,0 +1,86 @@ +Imports System.IO +Imports System.Xml +Imports System.Xml.Xsl +Imports System.Security.Policy +Imports System.Security +Imports System.Security.Permissions +Imports System.Net +Imports System.Reflection + +Class XmlSecureResolver_Samples + + Shared Sub Main() + + End Sub + + Public Sub Assembly_Evidence() + ' + Dim myEvidence As Evidence = Me.GetType().Assembly.Evidence + Dim myResolver As XmlSecureResolver + myResolver = New XmlSecureResolver(New XmlUrlResolver(), myEvidence) + ' + End Sub + + '============================== + ' + Shared Sub URI_Evidence() + Dim sourceURI As String = "http://serverName/data" + ' + Dim myEvidence As Evidence = XmlSecureResolver.CreateEvidenceForUrl(sourceURI) + Dim myResolver As New XmlSecureResolver(New XmlUrlResolver(), myEvidence) + ' + End Sub + + '============================== + ' + Shared Sub Use_URL() + ' + Dim myResolver As New XmlSecureResolver(New XmlUrlResolver(), "http://myLocalSite/") + ' + End Sub + + '============================== + ' + Shared Sub Use_PermissionSet() + ' + Dim myWebPermission As New WebPermission(PermissionState.None) + ' + ' + myWebPermission.AddPermission(NetworkAccess.Connect, "http://www.contoso.com/") + myWebPermission.AddPermission(NetworkAccess.Connect, "http://litwareinc.com/data/") + ' + ' + Dim myPermissions As New PermissionSet(PermissionState.None) + myPermissions.AddPermission(myWebPermission) + ' + ' + Dim myResolver As New XmlSecureResolver(New XmlUrlResolver(), myPermissions) + ' + End Sub + + '============================== + ' + Shared Sub Reader_Resolver() + Dim myResolver As New XmlSecureResolver(New XmlUrlResolver(), "http://myLocalSite/") + ' + Dim settings As New XmlReaderSettings() + settings.XmlResolver = myResolver + ' + ' + Dim reader As XmlReader = XmlReader.Create("books.xml", settings) + ' + End Sub + + '============================== + ' + Shared Sub XSLT_Resolver() + Dim myResolver As New XmlSecureResolver(New XmlUrlResolver(), "http://myLocalSite/") + ' + Dim xslt As New XslCompiledTransform() + xslt.Load("http://serverName/data/xsl/sort.xsl", Nothing, myResolver) + ' + End Sub + +End Class + + diff --git a/snippets/visualbasic/System.Xml/XmlWriter/Overview/Project.vbproj b/snippets/visualbasic/System.Xml/XmlWriter/Overview/Project.vbproj new file mode 100644 index 00000000000..874c98f3477 --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlWriter/Overview/Project.vbproj @@ -0,0 +1,8 @@ + + + + Library + net10.0 + + + diff --git a/snippets/visualbasic/System.Xml/XmlWriter/Overview/writer_v2.vb b/snippets/visualbasic/System.Xml/XmlWriter/Overview/writer_v2.vb new file mode 100644 index 00000000000..e9360e2e4ff --- /dev/null +++ b/snippets/visualbasic/System.Xml/XmlWriter/Overview/writer_v2.vb @@ -0,0 +1,256 @@ +Imports System.Text +Imports System.IO +Imports System.Xml + +Class Whidbey_Write_Methods + + + Shared Sub Main() + + End Sub + + ' WriteQName(); + + +Public Shared Sub WriteDateTime() +' +Dim price As [Double] = 9.95 +Dim [date] As New DateTime(2004, 5, 20) + +Using writer As XmlWriter = XmlWriter.Create("data.xml") + writer.WriteStartElement("book") + writer.WriteStartAttribute("pub-date") + writer.WriteValue([date]) + writer.WriteEndAttribute() + + writer.WriteStartElement("price") + writer.WriteValue(price) + writer.WriteEndElement() + + writer.WriteEndElement() + writer.Flush() +End Using +' +End Sub + + +Public Shared Sub CreateURI() +' +Using writer As XmlWriter = XmlWriter.Create("output.xml") + writer.WriteStartElement("book") + writer.WriteElementString("price", "19.95") + writer.WriteEndElement() + writer.Flush() +End Using +' +End Sub + +Public Shared Sub Create_Console() +' +Using writer As XmlWriter = XmlWriter.Create(Console.Out) + writer.WriteStartElement("book") + writer.WriteElementString("price", "19.95") + writer.WriteEndElement() + writer.Flush() +End Using +' +End Sub + +Public Shared Sub Create_StringWriter() +' +Dim settings As New XmlWriterSettings() +settings.OmitXmlDeclaration = True +Dim sw As New StringWriter() + +Using writer As XmlWriter = XmlWriter.Create(sw, settings) + writer.WriteStartElement("book") + writer.WriteElementString("price", "19.95") + writer.WriteEndElement() + writer.Flush() + + Dim output As String = sw.ToString() +End Using + ' +End Sub + +Public Shared Sub WriteQName() +' +Dim settings As New XmlWriterSettings() +settings.Indent = True +settings.OmitXmlDeclaration = True +Using writer As XmlWriter = XmlWriter.Create(Console.Out, settings) + writer.WriteStartElement("root") + writer.WriteAttributeString("xmlns", "x", Nothing, "urn:abc") + writer.WriteStartElement("item") + writer.WriteStartAttribute("href", Nothing) + writer.WriteString("#") + writer.WriteQualifiedName("test", "urn:abc") + writer.WriteEndAttribute() + writer.WriteEndElement() + writer.WriteEndElement() +End Using +' +End Sub + + +' # 6 placeholder for XmlQualfieldName.Empty snippet + +Public Shared Sub GenericCreate() +' +Dim settings As New XmlWriterSettings() +settings.Indent = True +settings.IndentChars = " " +Using writer As XmlWriter = XmlWriter.Create("books.xml", settings) + ' Write XML data. + writer.WriteStartElement("book") + writer.WriteElementString("price", "19.95") + writer.WriteEndElement() + writer.Flush() +End Using +' +End Sub + +Public Shared Sub Output1() +' +Dim settings As New XmlWriterSettings() +settings.Indent = True +settings.IndentChars = vbTab +Dim writer As XmlWriter = XmlWriter.Create("books.xml", settings) +' +End Sub + +Public Shared Sub Output2() +' +Dim settings As New XmlWriterSettings() +settings.Indent = True +settings.NewLineOnAttributes = True +Dim writer As XmlWriter = XmlWriter.Create("books.xml", settings) +' +End Sub + +Public Shared Sub Attrs1() +' +Dim settings As New XmlWriterSettings() +settings.Indent = True +Using writer As XmlWriter = XmlWriter.Create(Console.Out, settings) + writer.WriteStartElement("Product") + writer.WriteAttributeString("supplierID", "A23-1") + writer.WriteElementString("ProductID", "12345") + writer.WriteEndElement() +End Using +' +End Sub + +Public Shared Sub Attrs2() +' +Dim hireDate As New DateTime(2008, 5, 20) +Dim settings As New XmlWriterSettings() +settings.Indent = True +Using writer As XmlWriter = XmlWriter.Create(Console.Out, settings) + writer.WriteStartElement("Employee") + writer.WriteStartAttribute("review-date") + writer.WriteValue(hireDate.AddMonths(6)) + writer.WriteEndAttribute() + writer.WriteElementString("EmployeeID", "12345") + writer.WriteEndElement() +End Using +' +End Sub + +Public Shared Sub Attrs3() +' +Dim reader As XmlReader = XmlReader.Create("book.xml") +reader.ReadToDescendant("book") +Dim settings As New XmlWriterSettings() +settings.Indent = True +Using writer As XmlWriter = XmlWriter.Create(Console.Out, settings) + writer.WriteStartElement("root") + writer.WriteAttributes(reader, True) + writer.WriteEndElement() +End Using +' +End Sub + +Public Shared Sub Elems1() +Dim writer As XmlWriter = XmlWriter.Create(Console.Out) +' +writer.WriteElementString("price", "19.95") +' +writer.Flush() +End Sub + +Public Shared Sub Elems2() +Dim writer As XmlWriter = XmlWriter.Create(Console.Out) +' +writer.WriteStartElement("bk", "book", "urn:books") +writer.WriteAttributeString("genre", "urn:books", "mystery") +writer.WriteElementString("price", "19.95") +writer.WriteEndElement() +' +writer.Flush() +End Sub + +Public Shared Sub Elems3() +' +' Create a reader and position it on the book node. +Dim reader As XmlReader = XmlReader.Create("books.xml") +reader.ReadToFollowing("book") + +' Write out the book node. +Dim writer As XmlWriter = XmlWriter.Create("newBook.xml") +writer.WriteNode(reader, True) +writer.Flush() +' +End Sub + +Public Shared Sub TypedWrite() +' Create a reader and position it on the book node. +Dim reader As XmlReader = XmlReader.Create("books.xml") +Dim writer As XmlWriter = XmlWriter.Create(Console.Out) +' +reader.ReadToDescendant("price") +writer.WriteStartElement("price") +writer.WriteValue(reader.ReadElementContentAsDouble() * 1.15) +writer.WriteEndElement() +' +writer.Flush() +End Sub + +Public Shared Sub Namespace1() +Dim writer As XmlWriter = XmlWriter.Create(Console.Out) +' +writer.WriteStartElement("root") +writer.WriteAttributeString("xmlns", "x", Nothing, "urn:1") +writer.WriteStartElement("item", "urn:1") +writer.WriteEndElement() +writer.WriteStartElement("item", "urn:1") +writer.WriteEndElement() +writer.WriteEndElement() + ' +writer.Flush() +End Sub + +Public Shared Sub Namespace2() +Dim writer As XmlWriter = XmlWriter.Create(Console.Out) +' +writer.WriteStartElement("x", "root", "123") +writer.WriteStartElement("item") +writer.WriteAttributeString("xmlns", "x", Nothing, "abc") +writer.WriteEndElement() +writer.WriteEndElement() +' +writer.Flush() +End Sub + +Public Shared Sub Namespace3() +Dim writer As XmlWriter = XmlWriter.Create(Console.Out) +' +writer.WriteStartElement("x", "root", "urn:1") +writer.WriteStartElement("y", "item", "urn:1") +writer.WriteEndElement() +writer.WriteEndElement() +' +writer.Flush() +End Sub + +End Class diff --git a/xml/System.Xml.Linq/XName.xml b/xml/System.Xml.Linq/XName.xml index 37d3f5be0d6..a19f5a6a00e 100644 --- a/xml/System.Xml.Linq/XName.xml +++ b/xml/System.Xml.Linq/XName.xml @@ -64,7 +64,129 @@ Represents a name of an XML element or attribute. - For more information about this API, see Supplemental API remarks for XName. + + does not contain any public constructors. Instead, this class provides an implicit conversion from that allows you to create an . The most common place you use this conversion is when constructing an element or attribute: The first argument to the constructor is an . By passing a string, you take advantage of the implicit conversion. The following code creates an element with a name that is in no namespace: + +```csharp +XElement root = new XElement("ElementName", "content"); +Console.WriteLine(root); +``` + +In Visual Basic, it's more appropriate to use XML literals: + +```vb +Dim root As XElement = content +Console.WriteLine(root) +``` + +This example produces the following output: + +```xml +content +``` + +Assigning a string to an uses the implicit conversion from . + +The Visual Basic example creates the using XML literals. Even though XML literals are used, an object is created for the . + +In addition, you can call the method for an object. However, the recommended way is to use the implicit conversion from string. + +## Create an XName in a namespace + +As with XML, an can be in a namespace, or it can be in no namespace. + +For C#, the recommended approach for creating an in a namespace is to declare the object, then use the override of the addition operator. + +For Visual Basic, the recommended approach is to use XML literals and global namespace declarations to create XML that is in a namespace. + +```csharp +XNamespace aw = "http://www.adventure-works.com"; +XElement root = new XElement(aw + "ElementName", "content"); +Console.WriteLine(root); +``` + +```vb +Imports + +Module Module1 + Sub Main() + Dim root As XElement = content + Console.WriteLine(root) + End Sub +End Module +``` + +This example produces the following output: + +```xml +content +``` + +## Create an XName in no namespace + +The property of an object is guaranteed to not be null. If the is in no namespace, then the property will be set to . The following code demonstrates this: + +```csharp +XElement root = new XElement("ElementName", "content"); +if (root.Name.Namespace == XNamespace.None) + Console.WriteLine("The element is in no namespace."); +else + Console.WriteLine("The element is in a namespace."); +``` + +```vb +Dim root As XElement = content +If (root.Name.Namespace Is XNamespace.None) Then + Console.WriteLine("The element is in no namespace.") +Else + Console.WriteLine("The element is in a namespace.") +End If +``` + +This example produces the following output: + +``` +The element is in no namespace. +``` + +## Use expanded names + +You can also create an from a expanded XML name in the form `{namespace}localname`: + +```csharp +XElement root = new XElement("{http://www.adventure-works.com}ElementName", "content"); +Console.WriteLine(root); +``` + +```vb +Dim root As XElement = New XElement("{http://www.adventure-works.com}ElementName", "content") +Console.WriteLine(root) +``` + +This example produces the following output: + +```xml +content +``` + +Be aware that creating an through an expanded name is less efficient than creating an object and using the override of the addition operator. It is also less efficient than importing a global namespace and using XML literals in Visual Basic. + +If you create an using an expanded name, LINQ to XML must find the atomized instance of a namespace. This work must be repeated for every use of an expanded name. This additional time is likely to be negligible when writing LINQ queries; however, it might be significant when creating a large XML tree. + +## XName objects are atomized + + objects are guaranteed to be atomized; that is, if two objects have exactly the same namespace and exactly the same local name, they will share the same instance. The equality and comparison operators are also provided explicitly for this purpose. + +Among other benefits, this feature allows for faster execution of queries. When filtering on the name of elements or attributes, the comparisons expressed in predicates use identity comparison, not value comparison. It is much faster to determine that two references actually refer to the same object than to compare two strings. + + ]]> + LINQ to XML overview diff --git a/xml/System.Xml.Linq/XNamespace.xml b/xml/System.Xml.Linq/XNamespace.xml index c1d2858a6f5..302cd46b758 100644 --- a/xml/System.Xml.Linq/XNamespace.xml +++ b/xml/System.Xml.Linq/XNamespace.xml @@ -52,7 +52,179 @@ Represents an XML namespace. This class cannot be inherited. - For more information about this API, see Supplemental API remarks for XNamespace. + + contains an . Even if an element is not in a namespace, the element's still contains a namespace, . The property is guaranteed to not be `null`. + +## Create an XNamespace object + +The most common way to create an object is to simply assign a string to it. You can then combine the namespace with a local name by using the override of the addition operator. The following example shows this idiom: + +```csharp +XNamespace aw = "http://www.adventure-works.com"; +XElement root = new XElement(aw + "Root", "Content"); +Console.WriteLine(root); +``` + +```vb +Dim aw As XNamespace = "http://www.adventure-works.com" +Dim root As XElement = New XElement(aw + "Root", "Content") +Console.WriteLine(root) +``` + +However, in Visual Basic, you would typically declare a global default namespace, as follows: + +```vb +Imports + +Module Module1 + Sub Main() + Dim root As XElement = _ + Content + Console.WriteLine(root) + End Sub +End Module +``` + +This example produces the following output: + +```xml +Content +``` + +Assigning a string to an uses the implicit conversion from . + +See [How to create a document with namespaces in C# (LINQ to XML)](/dotnet/standard/linq/create-document-namespaces-csharp) for more information and examples. + +See [Work with XML namespaces](/dotnet/standard/linq/namespaces-overview) for more information on using namespaces in Visual Basic. + +## Control namespace prefixes + +If you create an attribute that declares a namespace, the prefix specified in the attribute will be persisted in the serialized XML. To create an attribute that declares a namespace with a prefix, you create an attribute where the namespace of the name of the attribute is , and the name of the attribute is the namespace prefix. The value of the attribute is the URI of the namespace. The following example shows this idiom: + +```csharp +XNamespace aw = "http://www.adventure-works.com"; +XElement root = new XElement(aw + "Root", + new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"), + "Content"); +Console.WriteLine(root); +``` + +```vb +Dim aw As XNamespace = "http://www.adventure-works.com" +Dim root As XElement = New XElement(aw + "Root", _ + New XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"), _ + "Content") +Console.WriteLine(root) +``` + +In Visual Basic, instead of creating a namespace node to control namespace prefixes, you would typically use a global namespace declaration: + +```vb +Imports + +Module Module1 + Sub Main() + Dim root As XElement = _ + Content + Console.WriteLine(root) + End Sub +End Module +``` + +This example produces the following output: + +``` +Content +``` + +For more information, see [How to control namespace prefixes](/dotnet/standard/linq/control-namespace-prefixes). + +## Create a default namespace + +When constructing an attribute that will be a namespace, if the attribute name has the special value of "xmlns", then when the XML tree is serialized, the namespace will be declared as the default namespace. The special attribute with the name of "xmlns" itself is not in any namespace. The value of the attribute is the namespace URI. + +The following example creates an XML tree that contains an attribute that is declared in such a way that the namespace will become the default namespace: + +```csharp +XNamespace aw = "http://www.adventure-works.com"; +XElement root = new XElement(aw + "Root", + new XAttribute("xmlns", "http://www.adventure-works.com"), + new XElement(aw + "Child", "content") +); +Console.WriteLine(root); +``` + +```vb +Dim aw As XNamespace = "http://www.adventure-works.com" +Dim root As XElement = New XElement(aw + "Root", _ + New XAttribute("xmlns", "http://www.adventure-works.com"), _ + New XElement(aw + "Child", "content") _ +) +Console.WriteLine(root) +``` + +In Visual Basic, instead of creating a namespace node to create a default namespace, you would typically use a global default namespace declaration: + +```vb +Imports + +Module Module1 + Sub Main() + Dim root As XElement = _ + + content + + Console.WriteLine(root) + End Sub +End Module +``` + +This example produces the following output: + +``` + + content + +``` + +## XNamespace atomization + + objects are guaranteed to be atomized; that is, if two objects have exactly the same URI, they will share the same instance. The equality and comparison operators are provided explicitly for this purpose. + +## Use expanded names + +Another way to specify a namespace and a local name is to use an expanded name in the form `{namespace}name`: + +```csharp +XElement e = new XElement("{http://www.adventure-works.com}Root", + new XAttribute("{http://www.adventure-works.com}Att", "content") +); +Console.WriteLine(e); +``` + +```vb +Dim e As XElement = New XElement("{http://www.adventure-works.com}Root", _ + New XAttribute("{http://www.adventure-works.com}Att", "content") _ +) +Console.WriteLine(e) +``` + +This example produces the following output: + +``` + +``` + +This approach has performance implications. Each time that you pass a string that contains an expanded name to LINQ to XML, it must parse the name, find the atomized namespace, and find the atomized name. This process takes CPU time. If performance is important, you may want to use a different approach. + +With Visual Basic, the recommended approach is to use XML literals, which does not involve the use of expanded names. + + ]]> + LINQ to XML overview diff --git a/xml/System.Xml.Schema/XmlSchemaSet.xml b/xml/System.Xml.Schema/XmlSchemaSet.xml index 884a380dfa3..8606e8c16a5 100644 --- a/xml/System.Xml.Schema/XmlSchemaSet.xml +++ b/xml/System.Xml.Schema/XmlSchemaSet.xml @@ -50,7 +50,51 @@ Contains a cache of XML Schema definition language (XSD) schemas. - For more information about this API, see Supplemental API remarks for XmlSchemaSet. + + [!IMPORTANT] +> +> - Do not use schemas from unknown or untrusted sources or locations. Doing so will compromise the security of your code. +> - XML schemas (including inline schemas) are inherently vulnerable to denial of service attacks; do not accept them in untrusted scenarios. +> - Schema validation error messages and exceptions may expose sensitive information about the content model or URI paths to the schema file. Be careful not to expose this information to untrusted callers. +> - Additional security considerations are covered in the "Security Considerations" section. + + is a cache or library where you can store XML Schema definition language (XSD) schemas. improves performance by caching schemas in memory instead of accessing them from a file or a URL. Each schema is identified by the namespace URI and location that was specified when the schema was added to the set. You use the property to assign the object an XML reader should use for data validation. + +## Security considerations + +- Do not use schemas from unknown or untrusted sources. Doing so will compromise the security of your code. External namespaces or locations referenced in include, import, and redefine elements of a schema are resolved with respect to the base URI of the schema that includes or imports them. For example, if the base URI of the including or importing schema is empty or `null`, the external locations are resolved with respect to the current directory. The class is used to resolve external schemas by default. To disable resolution of include, import, and redefine elements of a schema, set the property to `null`. + +- The class uses the class to parse and match regular expressions in an XML schema. Validation of pattern facets with regular expressions in an XML schema may involve increased CPU usage and should be avoided in high availability scenarios. + +- Exceptions raised as a result of using the class, such as the class may contain sensitive information that should not be exposed in untrusted scenarios. For example, the property of an returns the URI path to the schema file that caused the exception. The property should not be exposed in untrusted scenarios. Exceptions should be properly handled so that this sensitive information is not exposed in untrusted scenarios. + +## Examples + +The following example validates an XML file using schemas stored in the . The namespace in the XML file, `urn:bookstore-schema`, identifies which schema in the to use for validation. Output from the example shows that the XML file has two schema violations: + +- The first `` element contains an `` element but no `` or `<price>` element. + +- The `<author>` element in the last `<book>` element is missing a `<first-name>` and `<last-name>` element and instead has an invalid `<name>` element. + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlReaderSettings/ValidationType/validschemaset.cs" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml.Schema/XmlSchemaSet/Overview/validschemaset.vb" id="Snippet1"::: + +## Input + +The sample uses the following two input files. + +**booksSchemaFail.xml:** + +:::code language="xml" source="~/snippets/csharp/System.Xml.Schema/XmlSchemaSet/Overview/xml/booksschemafail.xml" id="Snippet2"::: + +**books.xsd:** + +:::code language="xml" source="~/snippets/csharp/System.Xml.Schema/XmlSchemaSet/Overview/xml/books.xsd" id="Snippet3"::: + + ]]></format> + </remarks> </Docs> <Members> <MemberGroup MemberName=".ctor"> diff --git a/xml/System.Xml.Serialization/CodeGenerationOptions.xml b/xml/System.Xml.Serialization/CodeGenerationOptions.xml index 3e569a506dd..04b515e93a3 100644 --- a/xml/System.Xml.Serialization/CodeGenerationOptions.xml +++ b/xml/System.Xml.Serialization/CodeGenerationOptions.xml @@ -49,7 +49,26 @@ </Attributes> <Docs> <summary>Specifies various options to use when generating .NET types for use with an XML Web Service.</summary> - <remarks>For more information about this API, see <see href="/dotnet/fundamentals/runtime-libraries/system-xml-serialization-codegenerationoptions">Supplemental API remarks for CodeGenerationOptions</see>.</remarks> + <remarks> + <format type="text/markdown"><![CDATA[ + +A Web Service Description Language (WSDL) file typically describes a class in XML schema language as an `xsd:complex` type composed of various primitive `xsd:complex` and `xsd:simple` types. When generating a .NET class that represents a given `xsd:complex` type, you must choose how to represent the various primitive types it contains. + +By default, each primitive is implemented as a field. If you specify the `GenerateProperties` option, each primitive type is instead implemented as a property. + +## Ordering of serialization code + +The `GenerateOrder` member instructs the code generator to create the serialization code in a specific order as determined by the `Order` property of the following attributes: + +- <xref:System.Xml.Serialization.XmlAnyElementAttribute> +- <xref:System.Xml.Serialization.XmlArrayAttribute> +- <xref:System.Xml.Serialization.XmlElementAttribute> + +> [!NOTE] +> Once the `Order` property has been set on one public property or field in a type, it must be applied to all public properties and fields for that type and all inherited types. + + ]]></format> + </remarks> <example> <format type="text/markdown"><![CDATA[ The following example illustrates the use of the `CodeGenerationOptions` enumeration to specify the behavior of a <xref:System.Web.Services.Description.ServiceDescriptionImporter> object. diff --git a/xml/System.Xml.Serialization/XmlSerializer.xml b/xml/System.Xml.Serialization/XmlSerializer.xml index e7a091ab606..44969baf1b1 100644 --- a/xml/System.Xml.Serialization/XmlSerializer.xml +++ b/xml/System.Xml.Serialization/XmlSerializer.xml @@ -52,7 +52,201 @@ </Attributes> <Docs> <summary>Serializes and deserializes objects into and from XML documents. The <see cref="T:System.Xml.Serialization.XmlSerializer" /> enables you to control how objects are encoded into XML.</summary> - <remarks>For more information about this API, see <see href="/dotnet/fundamentals/runtime-libraries/system-xml-serialization-xmlserializer">Supplemental API remarks for XmlSerializer</see>.</remarks> + <remarks> + <format type="text/markdown"><![CDATA[ + +XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output. You can think of serialization as a way of saving the state of an object into a stream or buffer. For example, ASP.NET uses the <xref:System.Xml.Serialization.XmlSerializer> class to encode XML Web service messages. + +The data in your objects is described using programming language constructs like classes, fields, properties, primitive types, arrays, and even embedded XML in the form of <xref:System.Xml.XmlElement> or <xref:System.Xml.XmlAttribute> objects. You have the option of creating your own classes, annotated with attributes, or using the [XML Schema Definition Tool (Xsd.exe)](/dotnet/standard/serialization/xml-schema-definition-tool-xsd-exe) to generate the classes based on an existing XML Schema definition (XSD) document. If you have an XML Schema, you can run the Xsd.exe to produce a set of classes that are strongly typed to the schema and annotated with attributes to adhere to the schema when serialized. + +To transfer data between objects and XML requires a mapping from the programming language constructs to XML schema and from the XML schema to the programming language constructs. The <xref:System.Xml.Serialization.XmlSerializer> and related tools like Xsd.exe provide the bridge between these two technologies at both design time and runtime. At design time, use the Xsd.exe to produce an XML schema document (.xsd) from your custom classes or to produce classes from a given schema. In either case, the classes are annotated with custom attributes to instruct the <xref:System.Xml.Serialization.XmlSerializer> how to map between the XML schema system and the common language runtime. At runtime, instances of the classes can be serialized into XML documents that follow the given schema. Likewise, these XML documents can be deserialized into runtime objects. Note that the XML schema is optional, and not required at design time or runtime. + +## Control generated XML + +To control the generated XML, you can apply special attributes to classes and members. For example, to specify a different XML element name, apply an <xref:System.Xml.Serialization.XmlElementAttribute> to a public field or property, and set the <xref:System.Xml.Serialization.XmlElementAttribute.ElementName> property. For a complete list of similar attributes, see [Attributes That Control XML Serialization](/dotnet/standard/serialization/attributes-that-control-xml-serialization). You can also implement the <xref:System.Xml.Serialization.IXmlSerializable> interface to control the XML output. + +If the XML generated must conform to section 5 of the World Wide Consortium document, [Simple Object Access Protocol (SOAP) 1.1](https://www.w3.org/TR/2000/NOTE-SOAP-20000508/), you must construct the <xref:System.Xml.Serialization.XmlSerializer> with an <xref:System.Xml.Serialization.XmlTypeMapping>. To further control the encoded SOAP XML, use the attributes listed in [Attributes That Control Encoded SOAP Serialization](/dotnet/standard/serialization/attributes-that-control-encoded-soap-serialization). + +With the <xref:System.Xml.Serialization.XmlSerializer> you can take advantage of working with strongly typed classes and still have the flexibility of XML. Using fields or properties of type <xref:System.Xml.XmlElement>, <xref:System.Xml.XmlAttribute> or <xref:System.Xml.XmlNode> in your strongly typed classes, you can read parts of the XML document directly into XML objects. + +If you work with extensible XML schemas, you can also use the <xref:System.Xml.Serialization.XmlAnyElementAttribute> and <xref:System.Xml.Serialization.XmlAnyAttributeAttribute> attributes to serialize and deserialize elements or attributes that are not found in the original schema. To use the objects, apply an <xref:System.Xml.Serialization.XmlAnyElementAttribute> to a field that returns an array of <xref:System.Xml.XmlElement> objects, or apply an <xref:System.Xml.Serialization.XmlAnyAttributeAttribute> to a field that returns an array of <xref:System.Xml.XmlAttribute> objects. + +If a property or field returns a complex object (such as an array or a class instance), the <xref:System.Xml.Serialization.XmlSerializer> converts it to an element nested within the main XML document. For example, the first class in the following code returns an instance of the second class. + +```vb +Public Class MyClass + Public MyObjectProperty As MyObject +End Class + +Public Class MyObject + Public ObjectName As String +End Class +``` + +```csharp +public class MyClass +{ + public MyObject MyObjectProperty; +} +public class MyObject +{ + public string ObjectName; +} +``` + +The serialized, XML output looks like this: + +```xml +<MyClass> + <MyObjectProperty> + <ObjectName>My String</ObjectName> + </MyObjectProperty> +</MyClass> +``` + +If a schema includes an element that is optional (minOccurs = '0'), or if the schema includes a default value, you have two options. One option is to use <xref:System.ComponentModel.DefaultValueAttribute?displayProperty=nameWithType> to specify the default value, as shown in the following code. + +```vb +Public Class PurchaseOrder + <System.ComponentModel.DefaultValueAttribute ("2002")> _ + Public Year As String +End Class +``` + +```csharp +public class PurchaseOrder +{ + [System.ComponentModel.DefaultValueAttribute ("2002")] + public string Year; +} +``` + +Another option is to use a special pattern to create a Boolean field recognized by the <xref:System.Xml.Serialization.XmlSerializer>, and to apply the <xref:System.Xml.Serialization.XmlIgnoreAttribute> to the field. The pattern is created in the form of `propertyNameSpecified`. For example, if there is a field named "MyFirstName" you would also create a field named "MyFirstNameSpecified" that instructs the <xref:System.Xml.Serialization.XmlSerializer> whether to generate the XML element named "MyFirstName". This is shown in the following example. + +```vb +Public Class OptionalOrder + ' This field's value should not be serialized + ' if it is uninitialized. + Public FirstOrder As String + + ' Use the XmlIgnoreAttribute to ignore the + ' special field named "FirstOrderSpecified". + <System.Xml.Serialization.XmlIgnoreAttribute> _ + Public FirstOrderSpecified As Boolean +End Class +``` + +```csharp +public class OptionalOrder +{ + // This field should not be serialized + // if it is uninitialized. + public string FirstOrder; + + // Use the XmlIgnoreAttribute to ignore the + // special field named "FirstOrderSpecified". + [System.Xml.Serialization.XmlIgnoreAttribute] + public bool FirstOrderSpecified; +} +``` + +## Override default serialization + +You can also override the serialization of any set of objects and their fields and properties by creating one of the appropriate attributes, and adding it to an instance of the <xref:System.Xml.Serialization.XmlAttributes> class. Overriding serialization in this way has two uses: first, you can control and augment the serialization of objects found in a DLL, even if you do not have access to the source; second, you can create one set of serializable classes, but serialize the objects in multiple ways. For more details, see the <xref:System.Xml.Serialization.XmlAttributeOverrides> class and [How to: Control Serialization of Derived Classes](/dotnet/standard/serialization/how-to-control-serialization-of-derived-classes). + +To serialize an object, call the <xref:System.Xml.Serialization.XmlSerializer.Serialize*> method. To deserialize an object, call the <xref:System.Xml.Serialization.XmlSerializer.Deserialize*> method. + +To add XML namespaces to an XML document, see <xref:System.Xml.Serialization.XmlSerializerNamespaces>. + +> [!NOTE] +> The <xref:System.Xml.Serialization.XmlSerializer> gives special treatment to classes that implement <xref:System.Collections.IEnumerable> or <xref:System.Collections.ICollection>. A class that implements <xref:System.Collections.IEnumerable> must implement a public `Add` method that takes a single parameter. The `Add` method's parameter must be of the same type as is returned from the `Current` property on the value returned from `GetEnumerator`, or one of that type's bases. A class that implements <xref:System.Collections.ICollection> (such as <xref:System.Collections.CollectionBase>) in addition to <xref:System.Collections.IEnumerable> must have a public `Item` indexed property (indexer in C#) that takes an integer, and it must have a public `Count` property of type integer. The parameter to the `Add` method must be the same type as is returned from the `Item` property, or one of that type's bases. For classes that implement <xref:System.Collections.ICollection>, values to be serialized are retrieved from the indexed `Item` property, not by calling `GetEnumerator`. + +You must have permission to write to the temporary directory (as defined by the TEMP environment variable) to deserialize an object. + +## Dynamically generated assemblies + +To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types. The infrastructure finds and reuses those assemblies. This behavior occurs only when using the following constructors: + +<xref:System.Xml.Serialization.XmlSerializer.%23ctor(System.Type)?displayProperty=nameWithType> + +<xref:System.Xml.Serialization.XmlSerializer.%23ctor(System.Type,System.String)?displayProperty=nameWithType> + +If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance. The easiest solution is to use one of the previously mentioned two constructors. Otherwise, you must cache the assemblies in a <xref:System.Collections.Hashtable>, as shown in the following example. + +```csharp +Hashtable serializers = new Hashtable(); + +// Use the constructor that takes a type and XmlRootAttribute. +XmlSerializer s = new XmlSerializer(typeof(MyClass), myRoot); + +// Implement a method named GenerateKey that creates unique keys +// for each instance of the XmlSerializer. The code should take +// into account all parameters passed to the XmlSerializer +// constructor. +object key = GenerateKey(typeof(MyClass), myRoot); + +// Check the local cache for a matching serializer. +XmlSerializer ser = (XmlSerializer)serializers[key]; +if (ser == null) +{ + ser = new XmlSerializer(typeof(MyClass), myRoot); + // Cache the serializer. + serializers[key] = ser; +} + +// Use the serializer to serialize or deserialize. +``` + +```vb +Dim serializers As New Hashtable() + +' Use the constructor that takes a type and XmlRootAttribute. +Dim s As New XmlSerializer(GetType([MyClass]), myRoot) + +' Implement a method named GenerateKey that creates unique keys +' for each instance of the XmlSerializer. The code should take +' into account all parameters passed to the XmlSerializer +' constructor. +Dim key As Object = GenerateKey(GetType([MyClass]), myRoot) + +' Check the local cache for a matching serializer. +Dim ser As XmlSerializer = CType(serializers(key), XmlSerializer) + +If ser Is Nothing Then + ser = New XmlSerializer(GetType([MyClass]), myRoot) + ' Cache the serializer. + serializers(key) = ser +End If + +' Use the serializer to serialize or deserialize. +``` + +## Serialization of ArrayList and generic list + +The <xref:System.Xml.Serialization.XmlSerializer> cannot serialize or deserialize the following: + +- Arrays of <xref:System.Collections.ArrayList> +- Arrays of <xref:System.Collections.Generic.List`1> + +## Serialization of enumerations of unsigned Long + +The <xref:System.Xml.Serialization.XmlSerializer> cannot be instantiated to serialize an enumeration if the following conditions are true: The enumeration is of type unsigned long (`ulong` in C#) and the enumeration contains any member with a value larger than 9,223,372,036,854,775,807. For example, the following cannot be serialized. + +```csharp +public enum LargeNumbers: ulong +{ + a = 9223372036854775808 +} +// At runtime, the following code will fail. +xmlSerializer mySerializer=new XmlSerializer(typeof(LargeNumbers)); +``` + +## Obsolete types + +The <xref:System.Xml.Serialization.XmlSerializer> class does not serialize objects that are marked as `[Obsolete]`. + + ]]></format> + </remarks> <example> <format type="text/markdown"><![CDATA[ The following example contains two main classes: `PurchaseOrder` and `Test`. The `PurchaseOrder` class contains information about a single purchase. The `Test` class contains the methods that create the purchase order, and that read the created purchase order. diff --git a/xml/System.Xml.Xsl/XslCompiledTransform.xml b/xml/System.Xml.Xsl/XslCompiledTransform.xml index 9ba33c8231c..e62fb9b51f4 100644 --- a/xml/System.Xml.Xsl/XslCompiledTransform.xml +++ b/xml/System.Xml.Xsl/XslCompiledTransform.xml @@ -54,7 +54,33 @@ </Attributes> <Docs> <summary>Transforms XML data using an XSLT style sheet.</summary> - <remarks>For more information about this API, see <see href="/dotnet/fundamentals/runtime-libraries/system-xml-xsl-xslcompiledtransform">Supplemental API remarks for XslCompiledTransform</see>.</remarks> + <remarks> + <format type="text/markdown"><![CDATA[ + +The <xref:System.Xml.Xsl.XslCompiledTransform> class is an XSLT processor that supports the XSLT 1.0 syntax. It is a new implementation and includes performance gains when compared to the obsolete <xref:System.Xml.Xsl.XslTransform> class. The structure of the <xref:System.Xml.Xsl.XslCompiledTransform> class is very similar to the <xref:System.Xml.Xsl.XslTransform> class. The <xref:System.Xml.Xsl.XslCompiledTransform.Load*> method loads and compiles the style sheet, while the <xref:System.Xml.Xsl.XslCompiledTransform.Transform*> method executes the XSLT transform. + +Support for the XSLT `document()` function and embedded script blocks are disabled by default. These features can be enabled by creating an <xref:System.Xml.Xsl.XsltSettings> object and passing it to the <xref:System.Xml.Xsl.XslCompiledTransform.Load*> method. + +For more information, see [Using the XslCompiledTransform Class](/dotnet/standard/data/xml/using-the-xslcompiledtransform-class) and [Migrating From the XslTransform Class](/dotnet/standard/data/xml/migrating-from-the-xsltransform-class). + +## Security considerations + +When creating an application that uses the <xref:System.Xml.Xsl.XslCompiledTransform> class, you should be aware of the following items and their implications: + +- XSLT scripting is disabled by default. XSLT scripting should be enabled only if you require script support and you are working in a fully trusted environment. + +- The XSLT `document()` function is disabled by default. If you enable the `document()` function, restrict the resources that can be accessed by passing <xref:System.Xml.XmlResolver.ThrowingResolver> to the <xref:System.Xml.Xsl.XslCompiledTransform.Transform*> method. + +- Extension objects are enabled by default. If an <xref:System.Xml.Xsl.XsltArgumentList> object containing extension objects is passed to the <xref:System.Xml.Xsl.XslCompiledTransform.Transform*> method, they are utilized. + +- XSLT style sheets can include references to other files and embedded script blocks. A malicious user can exploit this by supplying you with data or style sheets that when executed can cause your system to process until the computer runs low on resources. + +- XSLT applications that run in a mixed trust environment can result in style sheet spoofing. For example, a malicious user can load an object with a harmful style sheet and hand it off to another user who subsequently calls the <xref:System.Xml.Xsl.XslCompiledTransform.Transform*> method and executes the transformation. + +These security issues can be mitigated by not enabling scripting or the `document()` function unless the style sheet comes from a trusted source, and by not accepting <xref:System.Xml.Xsl.XslCompiledTransform> objects, XSLT style sheets, or XML source data from an untrusted source. + + ]]></format> + </remarks> <example> <format type="text/markdown"><![CDATA[ The following example executes a transform and outputs to a file. @@ -669,14 +695,6 @@ xslt.Load(typeof(bookOrders)); An <xref:System.Xml.XmlReader> with default settings is used to load the style sheet. DTD processing is disabled on the <xref:System.Xml.XmlReader>. If you require DTD processing, create an <xref:System.Xml.XmlReader> with this feature enabled, and pass it to the <xref:System.Xml.Xsl.XslCompiledTransform.Load*> method. - - -## Examples - The following example loads a style sheet that is stored on a network resource. An <xref:System.Xml.XmlSecureResolver> object specifies the credentials necessary to access the style sheet. - - :::code language="csharp" source="~/snippets/csharp/System.Xml/XmlResolver/Overview/Xslt_Load_v2.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Data/XslCompiledTransform.Load/VB/Xslt_Load_v2.vb" id="Snippet2"::: - ]]></format> </remarks> <exception cref="T:System.ArgumentNullException">The <paramref name="stylesheetUri" /> or <paramref name="stylesheetResolver" /> value is <see langword="null" />.</exception> @@ -829,14 +847,6 @@ xslt.Load(typeof(bookOrders)); ## Remarks The <xref:System.Xml.Xsl.XslCompiledTransform> class supports the XSLT 1.0 syntax. The XSLT style sheet must use the `http://www.w3.org/1999/XSL/Transform` namespace. - - -## Examples - The following example loads a style sheet. The <xref:System.Xml.XmlSecureResolver> object contains the credentials necessary to access any `import` or `include` elements found in the style sheet. - - :::code language="csharp" source="~/snippets/csharp/System.Xml/XmlResolver/Overview/Xslt_Load_v2.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Data/XslCompiledTransform.Load/VB/Xslt_Load_v2.vb" id="Snippet4"::: - ]]></format> </remarks> <exception cref="T:System.ArgumentNullException">The <paramref name="stylesheet" /> value is <see langword="null" />.</exception> @@ -2003,17 +2013,7 @@ xslt.Load(typeof(bookOrders)); If the style sheet contains an <c>xsl:output</c> element, you should create the <see cref="T:System.Xml.XmlWriter" /> using the <see cref="T:System.Xml.XmlWriterSettings" /> object returned from the <see cref="P:System.Xml.Xsl.XslCompiledTransform.OutputSettings" /> property. This ensures that the <see cref="T:System.Xml.XmlWriter" /> has the correct output settings.</param> <param name="documentResolver">The <see cref="T:System.Xml.XmlResolver" /> used to resolve the XSLT <c>document()</c> function. If this is <see langword="null" />, the <c>document()</c> function is not resolved.</param> <summary>Executes the transform using the input document specified by the <see cref="T:System.Xml.XmlReader" /> object and outputs the results to an <see cref="T:System.Xml.XmlWriter" />. The <see cref="T:System.Xml.Xsl.XsltArgumentList" /> provides additional run-time arguments and the XmlResolver resolves the XSLT <c>document()</c> function.</summary> - <remarks> - <format type="text/markdown"><![CDATA[ - -## Examples - The following example uses an <xref:System.Xml.XmlSecureResolver> to resolve the XSLT `document()` function. - - :::code language="csharp" source="~/snippets/csharp/System.Xml.Xsl/XslCompiledTransform/Overview/Xslt_Transform_v2.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Data/XslCompiledTransform.Transform/VB/Xslt_Transform_v2.vb" id="Snippet4"::: - - ]]></format> - </remarks> + <remarks>To be added.</remarks> <exception cref="T:System.ArgumentNullException">The <paramref name="input" /> or <paramref name="results" /> value is <see langword="null" />.</exception> <exception cref="T:System.Xml.Xsl.XsltException">There was an error executing the XSLT transform.</exception> <related type="Article" href="/dotnet/standard/data/xml/using-the-xslcompiledtransform-class">Using the XslCompiledTransform Class</related> diff --git a/xml/System.Xml.Xsl/XslTransform.xml b/xml/System.Xml.Xsl/XslTransform.xml index ceae4f4f071..13d97d461a1 100644 --- a/xml/System.Xml.Xsl/XslTransform.xml +++ b/xml/System.Xml.Xsl/XslTransform.xml @@ -373,7 +373,6 @@ <altmember cref="P:System.Xml.XmlResolver.Credentials" /> <altmember cref="T:System.Net.CredentialCache" /> <altmember cref="T:System.Net.NetworkCredential" /> - <altmember cref="T:System.Xml.XmlSecureResolver" /> </Docs> </Member> <Member MemberName="Load"> @@ -792,7 +791,6 @@ <remarks>To be added.</remarks> <altmember cref="T:System.Net.NetworkCredential" /> <altmember cref="T:System.Net.CredentialCache" /> - <altmember cref="T:System.Xml.XmlSecureResolver" /> </Docs> </Member> <Member MemberName="Transform"> @@ -976,7 +974,6 @@ <summary>Transforms the XML data in the <see cref="T:System.Xml.XPath.IXPathNavigable" /> using the specified <paramref name="args" /> and outputs the result to an <see cref="T:System.Xml.XmlReader" />.</summary> <returns>An <see cref="T:System.Xml.XmlReader" /> containing the results of the transformation.</returns> <remarks>To be added.</remarks> - <altmember cref="T:System.Xml.XmlSecureResolver" /> </Docs> </Member> <Member MemberName="Transform"> @@ -1221,7 +1218,6 @@ <returns>An <see cref="T:System.Xml.XmlReader" /> containing the results of the transformation.</returns> <remarks>To be added.</remarks> <exception cref="T:System.InvalidOperationException">There was an error processing the XSLT transformation..</exception> - <altmember cref="T:System.Xml.XmlSecureResolver" /> </Docs> </Member> <Member MemberName="Transform"> @@ -1350,7 +1346,6 @@ <summary>Transforms the XML data in the <see cref="T:System.Xml.XPath.IXPathNavigable" /> using the specified <paramref name="args" /> and outputs the result to a <see cref="T:System.IO.Stream" />.</summary> <remarks>To be added.</remarks> <exception cref="T:System.InvalidOperationException">There was an error processing the XSLT transformation.</exception> - <altmember cref="T:System.Xml.XmlSecureResolver" /> <altmember cref="P:System.Xml.XmlResolver.Credentials" /> </Docs> </Member> @@ -1421,7 +1416,6 @@ <summary>Transforms the XML data in the <see cref="T:System.Xml.XPath.IXPathNavigable" /> using the specified <paramref name="args" /> and outputs the result to a <see cref="T:System.IO.TextWriter" />.</summary> <remarks>To be added.</remarks> <exception cref="T:System.InvalidOperationException">There was an error processing the XSLT transformation.</exception> - <altmember cref="T:System.Xml.XmlSecureResolver" /> <altmember cref="P:System.Xml.XmlResolver.Credentials" /> </Docs> </Member> @@ -1492,7 +1486,6 @@ <summary>Transforms the XML data in the <see cref="T:System.Xml.XPath.IXPathNavigable" /> using the specified <paramref name="args" /> and outputs the result to an <see cref="T:System.Xml.XmlWriter" />.</summary> <remarks>To be added.</remarks> <exception cref="T:System.InvalidOperationException">There was an error processing the XSLT transformation.</exception> - <altmember cref="T:System.Xml.XmlSecureResolver" /> <altmember cref="P:System.Xml.XmlResolver.Credentials" /> </Docs> </Member> @@ -1564,7 +1557,6 @@ <remarks>To be added.</remarks> <exception cref="T:System.InvalidOperationException">There was an error processing the XSLT transformation.</exception> <altmember cref="T:System.Xml.Xsl.XsltArgumentList" /> - <altmember cref="T:System.Xml.XmlSecureResolver" /> <altmember cref="P:System.Xml.XmlResolver.Credentials" /> </Docs> </Member> @@ -1636,7 +1628,6 @@ <remarks>To be added.</remarks> <exception cref="T:System.InvalidOperationException">There was an error processing the XSLT transformation..</exception> <altmember cref="T:System.Xml.Xsl.XsltArgumentList" /> - <altmember cref="T:System.Xml.XmlSecureResolver" /> <altmember cref="P:System.Xml.XmlResolver.Credentials" /> </Docs> </Member> @@ -1708,7 +1699,6 @@ <remarks>To be added.</remarks> <exception cref="T:System.InvalidOperationException">There was an error processing the XSLT transformation..</exception> <altmember cref="T:System.Xml.Xsl.XsltArgumentList" /> - <altmember cref="T:System.Xml.XmlSecureResolver" /> <altmember cref="P:System.Xml.XmlResolver.Credentials" /> </Docs> </Member> diff --git a/xml/System.Xml.Xsl/XsltSettings.xml b/xml/System.Xml.Xsl/XsltSettings.xml index ba7c976ac47..59372f6614c 100644 --- a/xml/System.Xml.Xsl/XsltSettings.xml +++ b/xml/System.Xml.Xsl/XsltSettings.xml @@ -125,7 +125,7 @@ The new <xref:System.Xml.Xsl.XsltSettings> object does not support the XSLT `document()` function or embedded script blocks. > [!IMPORTANT] -> XSLT scripting should be enabled only if you require script support and you are working in a fully trusted environment. If you enable the `document()` function, you can restrict the resources that can be accessed by passing an <xref:System.Xml.XmlSecureResolver> object to the <xref:System.Xml.Xsl.XslCompiledTransform.Transform*> method. +> XSLT scripting should be enabled only if you require script support and you are working in a fully trusted environment. ]]></format> </remarks> @@ -180,9 +180,7 @@ ## Remarks > [!IMPORTANT] -> XSLT scripting should be enabled only if you require script support and you are working in a fully trusted environment. If you enable the `document()` function, you can restrict the resources that can be accessed by passing an <xref:System.Xml.XmlSecureResolver> object to the <xref:System.Xml.Xsl.XslCompiledTransform.Transform*> method. - - +> XSLT scripting should be enabled only if you require script support and you are working in a fully trusted environment. ## Examples The following example loads a style sheet and enables XSLT script support. @@ -292,7 +290,7 @@ ## Remarks > [!IMPORTANT] -> If you enable the `document()` function, you can restrict the resources that can be accessed by passing an <xref:System.Xml.XmlSecureResolver> object to the <xref:System.Xml.Xsl.XslCompiledTransform.Transform*> method. +> If you enable the `document()` function, you can restrict the resources that can be accessed by using <xref:System.Xml.XmlResolver.ThrowingResolver>. ]]></format> </remarks> @@ -402,9 +400,7 @@ ## Remarks > [!IMPORTANT] -> XSLT scripting should be enabled only if you require script support and you are working in a fully trusted environment. If you enable the `document()` function, you can restrict the resources that can be accessed by passing an <xref:System.Xml.XmlSecureResolver> object to the <xref:System.Xml.Xsl.XslCompiledTransform.Transform*> method. - - +> XSLT scripting should be enabled only if you require script support and you are working in a fully trusted environment. ## Examples The following example loads a style sheet with support for the XSLT `document()` function and embedded script blocks features enabled. diff --git a/xml/System.Xml/XmlConvert.xml b/xml/System.Xml/XmlConvert.xml index 8ee8482400f..fddf8022f81 100644 --- a/xml/System.Xml/XmlConvert.xml +++ b/xml/System.Xml/XmlConvert.xml @@ -57,7 +57,47 @@ </Attributes> <Docs> <summary>Encodes and decodes XML names, and provides methods for converting between common language runtime types and XML Schema definition language (XSD) types. When converting data types, the values returned are locale-independent.</summary> - <remarks>For more information about this API, see <see href="/dotnet/fundamentals/runtime-libraries/system-xml-xmlconvert">Supplemental API remarks for XmlConvert</see>.</remarks> + <remarks> + <format type="text/markdown"><![CDATA[ + +The <xref:System.Xml.XmlConvert> class is functionally equivalent to the <xref:System.Convert> class, but it supports XML standards. The type system is based on the XML Schema definition language (XSD) schema type, and the values returned are always locale-independent. + +## Encoding and decoding + +Element and attribute names or ID values are limited to a range of XML characters according to the W3C [XML 1.0 recommendation](https://www.w3.org/TR/2006/REC-xml-20060816/). When names contain invalid characters, you can use the <xref:System.Xml.XmlConvert.EncodeName*> and <xref:System.Xml.XmlConvert.DecodeName*> methods in this class to translate them into valid XML names. + +For example, if you want to use the column heading "Order Detail" in a database, the database allows the space between the two words. However, in XML, the space between "Order" and "Detail" is considered an invalid XML character. You have to convert it into an escaped hexadecimal encoding and decode it later. + +You can use the <xref:System.Xml.XmlConvert.EncodeName*> method with the <xref:System.Xml.XmlWriter> class to ensure the names being written are valid XML names. The following C# code converts the name "Order Detail" into a valid XML name and writes the element `<Order_0x0020_Detail>My order</Order_0x0020_Detail>`. + +```csharp +writer.WriteElementString(XmlConvert.EncodeName("Order Detail"),"My order"); +``` + +The following <xref:System.Xml.XmlConvert> methods perform encoding and decoding. + +|Method|Description| +|------------|-----------------| +|<xref:System.Xml.XmlConvert.EncodeName*>|Takes a name and returns the encoded name along with any invalid character that is replaced by an escape string. This method allows colons in any position, which means that the name may still be invalid according to the W3C [Namespaces in XML 1.0 recommendation](https://www.w3.org/TR/REC-xml-names/).| +|<xref:System.Xml.XmlConvert.EncodeNmToken*>|Takes a name and returns the encoded name.| +|<xref:System.Xml.XmlConvert.EncodeLocalName*>|Same as <xref:System.Xml.XmlConvert.EncodeName*> except that it also encodes the colon character, guaranteeing that the name can be used as the `LocalName` part of a namespace-qualified name.| +|<xref:System.Xml.XmlConvert.DecodeName*>|Reverses the transformation for all the encoding methods.| + +## Name validation + +The <xref:System.Xml.XmlConvert> class contains two methods that check the characters in an element or attribute name and verify that the name conforms to the rules set by the W3C [XML 1.0 recommendation](https://www.w3.org/TR/2006/REC-xml-20060816/): + +- <xref:System.Xml.XmlConvert.VerifyName*> checks the characters and verifies that the name is valid. The method returns the name if it's valid, and throws an exception if it isn't. +- <xref:System.Xml.XmlConvert.VerifyNCName*> performs the same validation, but accepts non-qualified names. + +The <xref:System.Xml.XmlConvert> contains additional methods that validate tokens, white-space characters, public IDs, and other strings. + +## Data type conversion + +<xref:System.Xml.XmlConvert> also provides methods that enable you to convert data from a string to a strongly typed data type. For example, the <xref:System.Xml.XmlConvert.ToDateTime*> method converts a string to its <xref:System.DateTime> equivalent. This is useful because most methods in the <xref:System.Xml.XmlReader> class return data as a string. After the data is read, it can be converted to the proper data type before being used. The <xref:System.Xml.XmlConvert.ToString*> overloads provide the complementary operation by converting strongly typed data to strings. For example, this is useful when you want to add the data to text boxes on a webpage. Locale settings are not taken into account during data conversion. The data types are based on the XML Schema (XSD) data types. + + ]]></format> + </remarks> </Docs> <Members> <Member MemberName=".ctor"> diff --git a/xml/System.Xml/XmlDocument.xml b/xml/System.Xml/XmlDocument.xml index cad8cffb886..b676a0aa654 100644 --- a/xml/System.Xml/XmlDocument.xml +++ b/xml/System.Xml/XmlDocument.xml @@ -66,7 +66,214 @@ </Attributes> <Docs> <summary>Represents an XML document. You can use this class to load, validate, edit, add, and position XML in a document.</summary> - <remarks>For more information about this API, see <see href="/dotnet/fundamentals/runtime-libraries/system-xml-xmldocument">Supplemental API remarks for XmlDocument</see>.</remarks> + <remarks> + <format type="text/markdown"><![CDATA[ + +The <xref:System.Xml.XmlDocument> class is an in-memory representation of an XML document. It implements the W3C [XML Document Object Model (DOM)](/dotnet/standard/data/xml/xml-document-object-model-dom) Level 1 Core and the Core DOM Level 2. + +*DOM* stands for *document object model*. To read more about it, see [XML Document Object Model (DOM)](/dotnet/standard/data/xml/xml-document-object-model-dom). + +You can load XML into the DOM by using the <xref:System.Xml.XmlDocument> class, and then programmatically read, modify, and remove XML in the document. + +If you want to pry open the <xref:System.Xml.XmlDocument> class and see how it's implemented, see the [Reference Source](https://referencesource.microsoft.com/#System.Xml/Xml/System/Xml/Dom/XmlDocument.cs#f82a4c1bd1f0ee12). + +## Load XML into the document object model + +Start with an XML document like this one that has a few books in a collection. It contains the basic things that you'd find in any XML document, including a namespace, elements that represent data, and attributes that describe the data. + +```xml +<?xml version="1.0" encoding="utf-8"?> +<books xmlns="http://www.contoso.com/books"> + <book genre="novel" ISBN="1-861001-57-8" publicationdate="1823-01-28"> + <title>Pride And Prejudice + 24.95 + + + The Handmaid's Tale + 29.95 + + + Sense and Sensibility + 19.95 + + +``` + +Next, load this data into the DOM so that you can work with it in memory. The most popular way to do this is refer to a file on your local computer or on a network. + +This example loads XML from a file. If the file doesn't exist, it just generates some XML and loads that. + +[!code-csharp[XMLProcessingApp#1](~/snippets/csharp/System.Xml/XmlDocument/Overview/xmlhelpermethods.cs#1)] +[!code-vb[XMLProcessingApp#1](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/xmlhelpermethods.vb#1)] + +For more information, see [Reading an XML Document into the DOM](/dotnet/standard/data/xml/reading-an-xml-document-into-the-dom). + +## Validate it against a schema + +Start with an XML schema like this one. This schema defines the data types in the XML and which attributes are required. + +```xml + + + + + + + + + + + + + + + + + + + + +``` + +Create an object by using your schema, and then load that object into the DOM. Create an event handler that executes when code attempts to modify your XML file in ways that violate the rules of the schema. + +These blocks of code show helper methods that do all of this. + +[!code-csharp[XMLProcessingApp#2](~/snippets/csharp/System.Xml/XmlDocument/Overview/xmlhelpermethods.cs#2)] +[!code-vb[XMLProcessingApp#2](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/xmlhelpermethods.vb#2)] + +For more information, see [Validating an XML Document in the DOM](/dotnet/standard/data/xml/validating-an-xml-document-in-the-dom). + +## Navigate the document tree + +You can use properties to navigate around an XML document. But before you use any of them, let's quickly review a few terms. Your document is composed of nodes. Each node has a single *parent* node directly above it. The only node that does not have a parent node is the document root, as it is the top-level node. Most nodes can have *child* nodes, which are nodes directly below them. Nodes that are at the same level are *siblings*. + +The following examples show you how to obtain the root node, jump to the first child node of the root node, access any of its child nodes, get back out to the parent node, and then navigate across sibling nodes. + +**Start with the root node** + +This example gets the root node and then uses that node to output the contents of the document to the console. + +[!code-csharp[Classic WebData XmlDocument.DocumentElement Example#1](~/snippets/csharp/System.Xml/XmlDocument/Overview/source.cs#1)] +[!code-vb[Classic WebData XmlDocument.DocumentElement Example#1](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-element.vb#1)] + +**Get child nodes** + +This example jumps to the first child node of the root node and then iterates through the child nodes of that node if any exist. + +[!code-csharp[Classic WebData XmlNode.HasChildNodes Example#1](~/snippets/csharp/System.Xml/XmlDocument/Overview/source2.cs#1)] +[!code-vb[Classic WebData XmlNode.HasChildNodes Example#1](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source2.vb#1)] + +**Get back to the parent node** + +Use the property. + +**Refer to the last child node** + +This example writes the price of a book to the console. The price node is the last child of a book node. + +[!code-csharp[Classic WebData XmlNode.LastChild Example#1](~/snippets/csharp/System.Xml/XmlDocument/Overview/source3.cs#1)] +[!code-vb[Classic WebData XmlNode.LastChild Example#1](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-lastchild.vb#1)] + +**Navigate forward across siblings** + +This example moves forward from book to book. Book nodes are siblings to one another. + +[!code-csharp[Classic WebData XmlNode.NextSibling Example#1](~/snippets/csharp/System.Xml/XmlDocument/Overview/source4.cs#1)] +[!code-vb[Classic WebData XmlNode.NextSibling Example#1](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-nextsibling.vb#1)] + +**Navigate backwards across siblings** + +This example moves backwards from book to book. + +[!code-csharp[Classic WebData XmlNode.PreviousSibling Example#1](~/snippets/csharp/System.Xml/XmlLinkedNode/PreviousSibling/source.cs#1)] +[!code-vb[Classic WebData XmlNode.PreviousSibling Example#1](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source5.vb#1)] + +## Find nodes + +The most popular way to find one or more nodes of data is to use an XPath query string, but there are also methods that don't require one. + +**Get a single node** + +This example locates a book by using the ISBN number. + +[!code-csharp[XMLProcessingApp#3](~/snippets/csharp/System.Xml/XmlDocument/Overview/xmlhelpermethods.cs#3)] +[!code-vb[XMLProcessingApp#3](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/xmlhelpermethods.vb#3)] + +The string used in this example is an Xpath query. You can find more examples of them at [XPath examples](/previous-versions/dotnet/netframework-4.0/ms256086(v=vs.100)). + +You can also use the to retrieve nodes. To use this approach, you'll have to define ID's in the document type definition declarations of your XML file. + +After you get a node, you get the value of attributes or child nodes. This example does that with a book node. + +[!code-csharp[XMLProcessingApp#4](~/snippets/csharp/System.Xml/XmlDocument/Overview/xmlhelpermethods.cs#4)] +[!code-vb[XMLProcessingApp#4](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/xmlhelpermethods.vb#4)] + +**Get a collection of nodes** + +This example selects all books where the author's last name is **Austen**, and then changes the price of those books. + +[!code-csharp[Classic WebData XmlNode.SelectNodes Example#1](~/snippets/csharp/System.Xml/XmlDocument/Overview/source6.cs#1)] +[!code-vb[Classic WebData XmlNode.SelectNodes Example#1](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/source.vb#1)] + +You can also get a collection of nodes by using the name of the node. For example, this example gets a collection of all book titles. + +[!code-csharp[Classic WebData XmlDocument.GetElementsByTagName Example#1](~/snippets/csharp/System.Xml/XmlDocument/Overview/source1.cs#1)] +[!code-vb[Classic WebData XmlDocument.GetElementsByTagName Example#1](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/Non-WinForms/source-tag.vb#1)] + +For more information, see [Select Nodes Using XPath Navigation](/dotnet/standard/data/xml/select-nodes-using-xpath-navigation). + +## Edit nodes + +This example edits a book node and its attributes. + +[!code-csharp[XMLProcessingApp#7](~/snippets/csharp/System.Xml/XmlDocument/Overview/xmlhelpermethods.cs#7)] +[!code-vb[XMLProcessingApp#7](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/xmlhelpermethods.vb#7)] + +For more information, see [Modifying Nodes, Content, and Values in an XML Document](/dotnet/standard/data/xml/modifying-nodes-content-and-values-in-an-xml-document). + +## Add nodes + +To add a node, use the method or the method. + +To add a data node such as a book, use the method. + +For any other type of node such as a comment, whitespace node, or CDATA node, use the method. + +This example creates a book node, adds attributes to that node, and then adds that node to the document. + +[!code-csharp[XMLProcessingApp#5](~/snippets/csharp/System.Xml/XmlDocument/Overview/xmlhelpermethods.cs#5)] +[!code-vb[XMLProcessingApp#5](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/xmlhelpermethods.vb#5)] + +For more information, see [Inserting Nodes into an XML Document](/dotnet/standard/data/xml/inserting-nodes-into-an-xml-document). + +## Remove nodes + +To remove a node, use the method. + +This example removes a book from the document and any whitespace that appears just before the book node. + +[!code-csharp[XMLProcessingApp#6](~/snippets/csharp/System.Xml/XmlDocument/Overview/xmlhelpermethods.cs#6)] +[!code-vb[XMLProcessingApp#6](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/xmlhelpermethods.vb#6)] + +For more information, see [Removing Nodes, Content, and Values from an XML Document](/dotnet/standard/data/xml/removing-nodes-content-and-values-from-an-xml-document). + +## Position nodes + +You can choose where you want a node to appear in your document by using the and methods. + +This example shows two helper methods. One of them moves a node higher in a list. The other one moves a node lower. + +These methods could be used in an application that enables users to move books up and down in a list of books. When a user chooses a book and presses an up or down button, your code could call methods like these to position the corresponding book node before or after other book nodes. + +[!code-csharp[XMLProcessingApp#8](~/snippets/csharp/System.Xml/XmlDocument/Overview/xmlhelpermethods.cs#8)] +[!code-vb[XMLProcessingApp#8](~/snippets/visualbasic/System.Xml/XmlDocument/Overview/WinForms/xmlhelpermethods.vb#8)] + + ]]> + @@ -5023,7 +5230,6 @@ The example uses the following data files as input. - diff --git a/xml/System.Xml/XmlReader.xml b/xml/System.Xml/XmlReader.xml index c5f089a8028..30586e88de5 100644 --- a/xml/System.Xml/XmlReader.xml +++ b/xml/System.Xml/XmlReader.xml @@ -62,7 +62,288 @@ Represents a reader that provides fast, noncached, forward-only access to XML data. - For more information about this API, see Supplemental API remarks for XmlReader. + + provides forward-only, read-only access to XML data in a document or stream. This class conforms to the W3C [Extensible Markup Language (XML) 1.0 (fourth edition)](https://www.w3.org/TR/2006/REC-xml-20060816/) and the [Namespaces in XML 1.0 (third edition)](https://www.w3.org/TR/REC-xml-names/) recommendations. + + methods let you move through XML data and read the contents of a node. The properties of the class reflect the value of the current node, which is where the reader is positioned. The property value indicates the current state of the XML reader. For example, the property is set to by the method and by the method. also provides data conformance checks and validation against a DTD or schema. + + uses a pull model to retrieve data. This model: + +- Simplifies state management by a natural, top-down procedural refinement. +- Supports multiple input streams and layering. +- Enables the client to give the parser a buffer into which the string is directly written, and thus avoids the necessity of an extra string copy. +- Supports selective processing. The client can skip items and process those that are of interest to the application. You can also set properties in advance to manage how the XML stream is processed (for example, normalization). + +## Create an XML reader + +Use the method to create an instance. + +Although .NET provides concrete implementations of the class, such as the , , and the classes, we recommend that you use the specialized classes only in these scenarios: + +- When you want to read an XML DOM subtree from an object, use the class. (However, this class doesn't support DTD or schema validation.) +- If you must expand entities on request, you don't want your text content normalized, or you don't want default attributes returned, use the class. + +To specify the set of features you want to enable on the XML reader, pass an object to the method. You can use a single object to create multiple readers with the same functionality, or modify the object to create a new reader with a different set of features. You can also easily add features to an existing reader. + +If you don't use a object, default settings are used. See the reference page for details. + + throws an on XML parse errors. After an exception is thrown, the state of the reader is not predictable. For example, the reported node type may be different from the actual node type of the current node. Use the property to check whether the reader is in error state. + +## Validate XML data + +To define the structure of an XML document and its element relationships, data types, and content constraints, you use a document type definition (DTD) or XML Schema definition language (XSD) schema. An XML document is considered to be well formed if it meets all the syntactical requirements defined by the [W3C XML 1.0 Recommendation](https://www.w3.org/TR/2006/REC-xml-20060816/). It's considered valid if it's well formed and also conforms to the constraints defined by its DTD or schema. (See the [W3C XML Schema Part 1: Structures](https://www.w3.org/TR/xmlschema-1/) and the [W3C XML Schema Part 2: Datatypes](https://www.w3.org/TR/xmlschema-2/) recommendations.) Therefore, although all valid XML documents are well formed, not all well-formed XML documents are valid. + +You can validate the data against a DTD, an inline XSD Schema, or an XSD Schema stored in an object (a cache); these scenarios are described on the reference page. doesn't support XML-Data Reduced (XDR) schema validation. + +You use the following settings on the class to specify what type of validation, if any, the instance supports. + +|Use this member|To specify| +|-----------------------------------------------------------------------------------------------------------------------------------------------------------|----------------| +| property|Whether to allow DTD processing. The default is to disallow DTD processing.| +| property|Whether the reader should validate data, and what type of validation to perform (DTD or schema). The default is no data validation.| +| event|An event handler for receiving information about validation events. If an event handler is not provided, an is thrown on the first validation error.| +| property|Additional validation options through the enumeration members:

- `AllowXmlAttributes`-- Allow XML attributes (`xml:*`) in instance documents even when they're not defined in the schema. The attributes are validated based on their data type. See the reference page for the setting to use in specific scenarios. (Disabled by default.)
- `ProcessIdentityConstraints` --Process identity constraints (`xs:ID`, `xs:IDREF`, `xs:key`, `xs:keyref`, `xs:unique`) encountered during validation. (Enabled by default.)
- `ProcessSchemaLocation` --Process schemas specified by the `xsi:schemaLocation` or `xsi:noNamespaceSchemaLocation` attribute. (Enabled by default.)
- `ProcessInlineSchema`-- Process inline XML Schemas during validation. (Disabled by default.)
- `ReportValidationWarnings`--Report events if a validation warning occurs. A warning is typically issued when there is no DTD or XML Schema to validate a particular element or attribute against. The is used for notification. (Disabled by default.)| +||The to use for validation.| +| property|The for resolving and accessing external resources. This can include external entities such as DTD and schemas, and any `xs:include` or `xs:import` elements contained in the XML Schema. If you don't specify an , the uses a default with no user credentials.| + +## Data conformance + +XML readers that are created by the method meet the following compliance requirements by default: + +- New lines and attribute value are normalized according to the W3C [XML 1.0 Recommendation](https://www.w3.org/TR/2006/REC-xml-20060816/). + +- All entities are automatically expanded. + +- Default attributes declared in the document type definition are always added even when the reader doesn't validate. + +- Declaration of XML prefix mapped to the correct XML namespace URI is allowed. + +- The notation names in a single `NotationType` attribute declaration and `NmTokens` in a single `Enumeration` attribute declaration are distinct. + +Use these properties to specify the type of conformance checks you want to enable: + +|Use this property|To|Default| +|-------------------------------------------------------------------------------------------------------------------------------------------------------------|--------|-------------| +| property|Enable or disable checks for the following:

- Characters are within the range of legal XML characters, as defined by the [2.2 Characters](https://www.w3.org/TR/2006/REC-xml-20060816/#charsets) section of the W3C XML 1.0 Recommendation.
- All XML names are valid, as defined by the [2.3 Common Syntactic Constructs](https://www.w3.org/TR/2006/REC-xml-20060816/#NT-Name) section of the W3C XML 1.0 Recommendation.

When this property is set to `true` (default), an exception is thrown if the XML file contains illegal characters or invalid XML names (for example, an element name starts with a number).|Character and name checking is enabled.

Setting to `false` turns off character checking for character entity references. If the reader is processing text data, it always checks that XML names are valid, regardless of this setting. **Note:** The XML 1.0 recommendation requires document-level conformance when a DTD is present. Therefore, if the reader is configured to support , but the XML data contains a document type definition (DTD), an is thrown.| +| property|Choose the level of conformance to enforce:

- . Conforms to the rules for a [well-formed XML 1.0 document](https://www.w3.org/TR/2006/REC-xml-20060816/#sec-well-formed).
- . Conforms to the rules for a well-formed document fragment that can be consumed as an [external parsed entity](https://www.w3.org/TR/2006/REC-xml-20060816/#wf-entities).
- . Conforms to the level decided by the reader.

If the data isn't in conformance, an exception is thrown.|| + +## Navigate through nodes + +The current node is the XML node on which the XML reader is currently positioned. All methods perform operations in relation to this node, and all properties reflect the value of the current node. + +The following methods make it easy to navigate through nodes and parse data. + +| Use this method | To | +|--------------------------------------------|----| +| | Read the first node, and advance through the stream one node at a time. Such calls are typically performed inside a `while` loop.

Use the property to get the type (for example, attribute, comment, element, and so on) of the current node. | +||Skip the children of the current node and move to the next node.| +| and |Skip non-content nodes and move to the next content node or to the end of the file.

Non-content nodes include , , , , and .

Content nodes include non-white space text, , , and .| +||Read an element and all its children, and return a new instance set to .

This method is useful for creating boundaries around XML elements; for example, if you want to pass data to another component for processing and you want to limit how much of your data the component can access.| + +See the reference page for an example of navigating through a text stream one node at a time and displaying the type of each node. + +The following sections describe how you can read specific types of data, such as elements, attributes, and typed data. + +## Read XML elements + +The following table lists the methods and properties that the class provides for processing elements. After the is positioned on an element, the node properties, such as , reflect the element values. In addition to the members described below, any of the general methods and properties of the class can also be used to process elements. For example, you can use the method to read the contents of an element. + +> [!NOTE] +> See section 3.1 of the [W3C XML 1.0 Recommendation](https://www.w3.org/TR/2006/REC-xml-20060816/#sec-starttags) for definitions of start tags, end tags, and empty element tags. + +|Use this member|To| +|---------------------------------------------------------------------------------------------------------------------------------------------------|--------| +| method|Check if the current node is a start tag or an empty element tag.| +| method|Check that the current node is an element and advance the reader to the next node (calls followed by ).| +| method|Check that the current node is an end tag and advance the reader to the next node.| +| method|Read a text-only element.| +| method|Advance the XML reader to the next descendant (child) element that has the specified name.| +| method|Advance the XML reader to the next sibling element that has the specified name.| +| property|Check if the current element has an end element tag. For example:

- `` ( is `true`.)
- ` ` ( is `false`, although the element's content is empty.)| + +For an example of reading the text content of elements, see the method. The following example processes elements by using a `while` loop. + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlReader/Overview/XmlReader_Basic.cs" id="Snippet10"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Overview/xmlreader_basic.vb" id="Snippet10"::: + +## Read XML attributes + +XML attributes are most commonly found on elements, but they're also allowed on XML declaration and document type nodes. + +When positioned on an element node, the method lets you go through the attribute list of the element. Note that after has been called, node properties such as , , and reflect the properties of that attribute, not the properties of the element the attribute belongs to. + +The class provides these methods and properties to read and process attributes on elements. + +|Use this member|To| +|---------------------------------------------------------------------------------------------------------------------------------------------------|--------| +| property|Check whether the current node has any attributes.| +| property|Get the number of attributes on the current element.| +| method|Move to the first attribute in an element.| +| method|Move to the next attribute in an element.| +| method|Move to a specified attribute.| +| method or property|Get the value of a specified attribute.| +| property|Check whether the current node is an attribute that was generated from the default value defined in the DTD or schema.| +| method|Move to the element that owns the current attribute. Use this method to return to an element after navigating through its attributes.| +| method|Parse the attribute value into one or more `Text`, `EntityReference`, or `EndEntity` nodes.| + +Any of the general methods and properties can also be used to process attributes. For example, after the is positioned on an attribute, the and properties reflect the values of the attribute. You can also use any of the content `Read` methods to get the value of the attribute. + +This example uses the property to navigate through all the attributes on an element. + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlReader/Overview/XmlReader_Basic.cs" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Overview/xmlreader_basic.vb" id="Snippet1"::: + +This example uses the method in a `while` loop to navigate through the attributes. + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlReader/Overview/XmlReader_Basic.cs" id="Snippet6"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Overview/xmlreader_basic.vb" id="Snippet6"::: + +**Reading attributes on XML declaration nodes** + +When the XML reader is positioned on an XML declaration node, the property returns the version, standalone, and encoding information as a single string. objects created by the method, the class, and the class expose the version, standalone, and encoding items as attributes. + +**Reading attributes on document type nodes** + +When the XML reader is positioned on a document type node, the method and property can be used to return the values for the SYSTEM and PUBLIC literals. For example, calling `reader.GetAttribute("PUBLIC")` returns the PUBLIC value. + +**Reading attributes on processing instruction nodes** + +When the is positioned on a processing instruction node, the property returns the entire text content. Items in the processing instruction node aren't treated as attributes. They can't be read with the or method. + +## Read XML content + +The XmlReader class includes the following members that read content from an XML file and return the content as string values. (To return CLR types, see [Convert to CLR types](#convert-to-clr-types).) + +|Use this member|To| +|---------------------------------------------------------------------------------------------------------------------------------------------------|--------| +| property|Get the text content of the current node. The value returned depends on the node type; see the reference page for details.| +| method|Get the content of an element or text node as a string. This method stops on processing instructions and comments.

For details on how this method handles specific node types, see the reference page.| +| and methods|Get all the content of the current node, including the markup, but excluding start and end tags. For example, for:

`this`

returns:

`this`| +| and methods|Get all the content of the current node and its children, including markup and start/end tags. For example, for:

`this`

returns:

`this`| + +## Convert to CLR types + +You can use the members of the class (listed in the following table) to read XML data and return values as common language runtime (CLR) types instead of strings. These members enable you to get values in the representation that is most appropriate for your coding task without having to manually parse or convert string values. + +- The **ReadElementContentAs** methods can only be called on element node types. These methods cannot be used on elements that contain child elements or mixed content. When called, the object reads the start tag, reads the element content, and then moves past the end element tag. Processing instructions and comments are ignored and entities are expanded. + +- The **ReadContentAs** methods read the text content at the current reader position, and if the XML data doesn't have any schema or data type information associated with it, convert the text content to the requested return type. Text, white space, significant white space and CDATA sections are concatenated. Comments and processing instructions are skipped, and entity references are automatically resolved. + +The class uses the rules defined by the [W3C XML Schema Part 2: Datatypes](https://www.w3.org/TR/xmlschema-2/) recommendation. + +|Use this method|To return this CLR type| +|--------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------| +| and || +| and || +| and || +| and || +| and || +| and || +| and |The type you specify with the `returnType` parameter| +| and |The most appropriate type, as specified by the property. See [Type Support in the System.Xml Classes](/dotnet/standard/data/xml/type-support-in-the-system-xml-classes) for mapping information.| + +If an element can't easily be converted to a CLR type because of its format, you can use a schema mapping to ensure a successful conversion. The following example uses an .xsd file to convert the `hire-date` element to the `xs:date` type, and then uses the method to return the element as a object. + +**Input (hireDate.xml):** + +:::code language="xml" source="~/snippets/csharp/System.Xml/XmlReader/Overview/xml/hireDate.xml" id="Snippet9"::: + +**Schema (hireDate.xsd):** + +:::code language="xml" source="~/snippets/csharp/System.Xml/XmlReader/Overview/xml/hireDate.xsd" id="Snippet10"::: + +**Code:** + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlReader/Overview/readElementContentAs.cs" id="Snippet13"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Overview/readElementContentAs.vb" id="Snippet13"::: + +**Output:** + +``` +Six Month Review Date: 7/8/2003 12:00:00 AM +``` + +## Asynchronous programming + +Most of the methods have asynchronous counterparts that have "Async" at the end of their method names. For example, the asynchronous equivalent of is . + +The following methods can be used with asynchronous method calls: + +- +- +- +- +- +- +- +- + +The following sections describe asynchronous usage for methods that don't have asynchronous counterparts. + +**ReadStartElement method** + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlReader/Overview/program.cs" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Overview/module1.vb" id="Snippet1"::: + +**ReadEndElement method** + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlReader/Overview/program.cs" id="Snippet2"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Overview/module1.vb" id="Snippet2"::: + +**ReadToNextSibling method** + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlReader/Overview/program.cs" id="Snippet3"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Overview/module1.vb" id="Snippet3"::: + +**ReadToFollowing method** + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlReader/Overview/program.cs" id="Snippet4"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Overview/module1.vb" id="Snippet4"::: + +**ReadToDescendant method** + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlReader/Overview/program.cs" id="Snippet5"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Overview/module1.vb" id="Snippet5"::: + +## Security considerations + +Consider the following when working with the class: + +- Exceptions thrown from the can disclose path information that you might not want bubbled up to your app. Your app must catch exceptions and process them appropriately. + +- Do not enable DTD processing if you're concerned about denial of service issues or if you're dealing with untrusted sources. DTD processing is disabled by default for objects created by the method. + +- XML data can include references to external resources such as a schema file. By default, external resources are resolved by using an object with no user credentials. You can secure this further by doing one of the following: + + - Use when attempting to forbid XML external entity resolution. + - Do not allow the to open any external resources by setting the property to `null`. + +- The and validation flags of an object aren't set by default. This helps to protect the against schema-based attacks when it is processing XML data from an untrusted source. When these flags are set, the of the object is used to resolve schema locations encountered in the instance document in the . If the property is set to `null`, schema locations aren't resolved even if the and validation flags are set. + + Schemas added during validation add new types and can change the validation outcome of the document being validated. As a result, external schemas should only be resolved from trusted sources. + + We recommend disabling the flag when validating untrusted, large XML documents in high availability scenarios against a schema that has identity constraints over a large part of the document. This flag is enabled by default. + +- XML data can contain a large number of attributes, namespace declarations, nested elements and so on that require a substantial amount of time to process. To limit the size of the input that is sent to the , you can: + + - Limit the size of the document by setting the property. + + - Limit the number of characters that result from expanding entities by setting the property. + + - Create a custom `IStream` implementation for the . + +- The method can be used to handle large streams of data. This method reads a small number of characters at a time instead of allocating a single string for the whole value. + +- When reading an XML document with a large number of unique local names, namespaces, or prefixes, a problem can occur. If you are using a class that derives from , and you call the , , or property for each item, the returned string is added to a . The collection held by the never decreases in size, creating a virtual memory leak of the string handles. One mitigation for this is to derive from the class and enforce a maximum size quota. (There is no way to prevent the use of a , or to switch the when it is full). Another mitigation is to avoid using the properties mentioned and instead use the method with the method where possible; those methods don't return strings and thus avoid the problem of overfilling the collection. + +- objects can contain sensitive information such as user credentials. An untrusted component could use the object and its user credentials to create objects to read data. Be careful when caching objects, or when passing the object from one component to another. + +- Do not accept supporting components, such as , , and objects, from an untrusted source. + + ]]>
+
, , , and methods. If this property returns `false` a is returned when any of the binary read methods is called. + The binary content read methods include the , , , and methods. If this property returns `false`, a is returned when any of the binary read methods is called. All .NET implementations of the class return `true` for this property. @@ -455,7 +736,92 @@ The following example code shows how to use the asynchronous API to parse XML. Creates a new instance. - For more information about this API, see Supplemental API remarks for XmlReader.Close. + + overloads include a `settings` parameter that accepts an object. You can use this object to: + +- Specify which features you want supported on the object. +- Reuse the object to create multiple readers. You can use the same settings to create multiple readers with the same functionality. Or, you can modify the settings on an instance and create a new reader with a different set of features. +- Add features to an existing XML reader. The method can accept another object. The underlying object can be a user-defined reader, a object, or another instance that you want to add additional features to. +- Take full advantage of features such as better conformance checking and compliance to the [XML 1.0 (fourth edition)](https://www.w3.org/TR/2006/REC-xml-20060816/) recommendation that are available only on objects created by the static method. + +> [!NOTE] +> Although .NET includes concrete implementations of the class, such as the , , and the classes, we recommend that you create instances by using the method. + +## Default settings + +If you use a overload that doesn't accept a object, the following default reader settings are used: + +| Setting | Default | +|---------------------------------------------------------------------|-------------------------------------------------------| +| | `true` | +| | | +| | `false` | +| | `false` | +| | `false` | +| | 0 | +| | 0 | +| | `null` | +| | | +| | An empty object | +| | enabled | +| | | +| | `null` | + +## Settings for common scenarios + +Here are the properties you should set for some of the typical XML reader scenarios. + +|Requirement|Set| +|-----------------|---------| +|Data must be a well-formed XML document.| to .| +|Data must be a well-formed XML parsed entity.| to .| +|Data must be validated against a DTD.| to
to .| +|Data must be validated against an XML schema.| to
to the to use for validation. Note that doesn't support XML-Data Reduced (XDR) schema validation.| +|Data must be validated against an inline XML schema.| to
to .| +|Type support.| to
to the to use.| + + doesn't support XML-Data Reduced (XDR) schema validation. + +## Asynchronous programming + +In synchronous mode, the method reads the first chunk of data from the buffer of the file, stream, or text reader. This may throw an exception if an I/O operation fails. In asynchronous mode, the first I/O operation occurs with a read operation, so exceptions that arise will be thrown when the read operation occurs. + +## Security considerations + +By default, the uses an object with no user credentials to open resources. This means that, by default, the XML reader can access any location that doesn't require credentials. Use the property to control access to resources: + +- Use to restrict the resources that the XML reader can access, or... +- Set to `null` to prevent the XML reader from opening any external resources. + +## Examples + +This example creates an XML reader that strips insignificant white space, strips comments, and performs fragment-level conformance checking. + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlParserContext/Overview/XmlReader_Create.cs" id="Snippet11"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Create/XmlReader_Create.vb" id="Snippet11"::: + +The following example uses an with default credentials to access a file. + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlReader/Create/factory_rdr_cctor21.cs" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Create/factory_rdr_cctor2.vb" id="Snippet1"::: + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlReader/Create/factory_rdr_cctor21.cs" id="Snippet2"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Create/factory_rdr_cctor2.vb" id="Snippet2"::: + +The following code wraps a reader instance within another reader. + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlParserContext/Overview/XmlReader_Create.cs" id="Snippet13"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Create/XmlReader_Create.vb" id="Snippet13"::: + +This example chains readers to add DTD and XML schema validation. + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlParserContext/Overview/XmlReader_Create.cs" id="Snippet12"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlReader/Create/XmlReader_Create.vb" id="Snippet12"::: + + ]]>
+
@@ -748,10 +1114,7 @@ The following example code shows how to use the asynchronous API to parse XML. > [!IMPORTANT] > You can use one of the following methods to control which resources the can access: > -> - Restrict the resources that the can access by setting the property to an object. -> -> -or- -> +> - Restrict the resources that the can access by using . > - Do not allow the to open any external resources by setting the property to `null`. The created object expands entity references and performs XML normalization of new line characters. @@ -829,10 +1192,7 @@ The following example code shows how to use the asynchronous API to parse XML. > [!IMPORTANT] > You can use one of the following methods to control which resources the can access: > -> - Restrict the resources that the can access by setting the property to an object. -> -> -or- -> +> - Restrict the resources that the can access by using . > - Do not allow the to open any external resources by setting the property to `null`. The created object expands entity references and performs XML normalization of new line characters. @@ -905,15 +1265,13 @@ The following example code shows how to use the asynchronous API to parse XML. > [!IMPORTANT] > No default is provided. Specify an using the property. - This means that the can access any locations that does not require authentication. If the external resource is located on a network resource that requires authentication, use the property to specify an with the necessary credentials. + This means that the can access any locations that don't require authentication. If the external resource is located on a network resource that requires authentication, use the property to specify an with the necessary credentials. > [!IMPORTANT] -> You can restrict the resources that the can access by setting the property to an object. +> You can restrict the resources that the can access by using . The created object expands entity references and performs XML normalization of new line characters. - - ## Examples The following example creates an object that supports document type definition (DTD) validation. @@ -999,10 +1357,7 @@ The following example code shows how to use the asynchronous API to parse XML. > [!IMPORTANT] > You can use one of the following methods to control which resources the can access: > -> - Restrict the resources that the can access by setting the property to an object. -> -> -or- -> +> - Restrict the resources that the can access by using . > - Do not allow the to open any external resources by setting the property to `null`. The created object expands entity references and performs XML normalization of new line characters. @@ -1104,10 +1459,7 @@ The following example code shows how to use the asynchronous API to parse XML. > [!IMPORTANT] > You can use one of the following methods to control which resources the can access: > -> - Restrict the resources that the can access by setting the property to an object. -> -> -or- -> +> - Restrict the resources that the can access by using . > - Do not allow the to open any external resources by setting the property to `null`. The created object expands entity references and performs XML normalization of new line characters. @@ -1198,10 +1550,7 @@ The following example code shows how to use the asynchronous API to parse XML. > [!IMPORTANT] > You can use one of the following methods to control which resources the can access: > -> - Restrict the resources that the can access by setting the property to an object. -> -> -or- -> +> - Restrict the resources that the can access by using . > - Do not allow the to open any external resources by setting the property to `null`. The created object expands entity references and performs XML normalization of new line characters. @@ -1288,10 +1637,7 @@ The following example code shows how to use the asynchronous API to parse XML. > [!IMPORTANT] > You can use one of the following methods to control which resources the can access: > -> - Restrict the resources that the can access by setting the property to an object. -> -> -or- -> +> - Restrict the resources that the can access by using . > - Do not allow the to open any external resources by setting the property to `null`. The created object expands entity references and performs XML normalization of new line characters. @@ -1380,10 +1726,7 @@ The following example code shows how to use the asynchronous API to parse XML. > [!IMPORTANT] > You can use one of the following methods to control which resources the can access: > -> - Restrict the resources that the can access by setting the property to an object. -> -> -or- -> +> - Restrict the resources that the can access by using . > - Do not allow the to open any external resources by setting the property to `null`. The created object expands entity references and performs XML normalization of new line characters. @@ -1474,10 +1817,10 @@ The following example code shows how to use the asynchronous API to parse XML. > [!IMPORTANT] > No default is provided. Specify an using the property. - This means that the can access any locations that does not require authentication. If the external resource is located on a network resource that requires authentication, use the property to specify an with the necessary credentials. +This means that the can access any locations that don't require authentication. If the external resource is located on a network resource that requires authentication, use the property to specify an with the necessary credentials. > [!IMPORTANT] -> You can restrict the resources that the can access by setting the property to an object. +> You can restrict the resources that the can access by using . The created object expands entity references and performs XML normalization of new line characters. diff --git a/xml/System.Xml/XmlReaderSettings.xml b/xml/System.Xml/XmlReaderSettings.xml index 3969af9ea8e..fba4d597c77 100644 --- a/xml/System.Xml/XmlReaderSettings.xml +++ b/xml/System.Xml/XmlReaderSettings.xml @@ -53,7 +53,37 @@ Specifies a set of features to support on the object created by the method. - For more information about this API, see Supplemental API remarks for XmlReaderSettings. + + method to obtain instances. This method uses the class to specify which features to implement in the object it creates. + +See the Remarks sections of the and reference pages for information about which settings to use for conformance checks, validation, and other common scenarios. See the constructor for a list of default settings. + +## Security considerations + +Consider the following when using the class. + +- The and validation flags of an object are not set by default. When these flags are set, the of the object is used to resolve schema locations encountered in the instance document in the . If the object is `null`, schema locations are not resolved even if the and validation flags are set. + +- Schemas added during validation add new types and can change the validation outcome of the document being validated. As a result, external schemas should only be resolved from trusted sources. + +- Validation error messages may expose sensitive content model information. Validation error and warning messages are handled using the delegate, or are exposed as an if no event handler is provided to the object (validation warnings do not cause an to be thrown). This content model information should not be exposed in untrusted scenarios. Validation warning messages are suppressed by default and can be reported by setting the flag. + +- The property of an returns the URI path to the schema file that caused the exception. The property should not be exposed in untrusted scenarios. + +- Disabling the flag (enabled by default) is recommended when validating, untrusted, large XML documents in high availability scenarios against a schema with identity constraints over a large part of the document. + +- objects can contain sensitive information such as user credentials. You should be careful when caching objects, or when passing the object from one component to another. + +- DTD processing is disabled by default. If you enable DTD processing, you need to be aware of including DTDs from untrusted sources and possible denial of service attacks. Use to restrict the resources that the can access. + +- Do not accept supporting components, such as , , and objects, from an untrusted source. + +- Memory usage of an application that uses may have a correlation to the size of the parsed XML document. One form of denial of service attack is when excessively large XML documents are submitted to be parsed. You can limit the size of the document that can be parsed by setting the property and then limit the number of characters that result from expanding entities by setting the property. + + ]]> + that uses an with the necessary credentials. @@ -509,7 +539,28 @@ If the is processing text data, it always checks tha Gets or sets a value that determines the processing of DTDs. One of the enumeration values that determines the processing of DTDs. The default is . - For more information about this API, see Supplemental API remarks for XmlReaderSettings.DtdProcessing. + + property can have one of the following values: + +- to enable DTD processing. +- to throw an exception when a DTD is encountered. +- to disable DTD processing without warnings or exceptions. + +To perform validation against a DTD, the uses the DTD defined in the DOCTYPE declaration of an XML document. The DOCTYPE declaration can either point to an inline DTD or can be a reference to an external DTD file. To validate an XML file against a DTD: + +- Set the property to `DtdProcessing.Parse`. +- Set the property to `ValidationType.DTD`. +- If the DTD is an external file stored on a network resource that requires authentication, pass an object with the necessary credentials to the method. + +> [!IMPORTANT] +> If the property is set to , the will not report the DTDs. This means that the DTD/DOCTYPE will be lost on output. + + ]]> + throws an when any DTD content is encountered. Do not enable DTD processing if you are concerned about Denial of Service issues or if you are dealing with untrusted sources. - If you have DTD processing enabled, you can use the to restrict the resources that the can access. You can also design your application so that the XML processing is memory and time constrained. For example, configure time-out limits in your ASP.NET application. + If you have DTD processing enabled, you can use to restrict the resources that the can access. You can also design your application so that the XML processing is memory and time constrained. For example, configure time-out limits in your ASP.NET application. This property is obsolete. Use instead. If you had set to its default value `true` set to `Prohibit`. If you had set to `false` set to `Parse`. @@ -1252,7 +1303,28 @@ There is an error in XML document (MaxCharactersInDocument, ). Gets or sets the to use when performing schema validation. The to use when performing schema validation. The default is an empty object. - For more information about this API, see Supplemental API remarks for XmlReaderSettings.Schemas. + + property. + +> [!IMPORTANT] +> +> - Do not use schemas from unknown or untrusted sources or locations. Doing so compromises the security of your code. +> - XML schemas (including inline schemas) are inherently vulnerable to denial of service attacks; do not accept them in untrusted scenarios. +> - Schema validation error messages and exceptions may expose sensitive information about the content model or URI paths to the schema file. Be careful not to expose this information to untrusted callers. +> - For additional information, see the "Security considerations" section. + +The class only supports XML Schema definition language (XSD) schemas. instances created by the method cannot be configured to enable XML-Data Reduced (XDR) schema validation. + +## Security considerations + +- Do not use schemas from unknown or untrusted sources. Doing so will compromise the security of your code. The class is used to resolve external schemas by default. To disable resolution of include, import, and redefine elements of a schema, set the property to `null`. + +- Exceptions raised as a result of using the class, such as the class may contain sensitive information that should not be exposed in untrusted scenarios. For example, the property of an returns the URI path to the schema file that caused the exception. The property should not be exposed in untrusted scenarios. Exceptions should be properly handled so that this sensitive information is not exposed in untrusted scenarios. + + ]]> + object and the method to associate a schema with an XML document. The schema is added to the property of the object. The value of the property is an object. The schema is used to validate that the XML document conforms to the schema content model. Schema validation errors and warnings are handled by the defined in the object. @@ -1535,18 +1607,12 @@ The output is as follows: > [!IMPORTANT] > Because the can contain sensitive information such as user credentials, you should be careful when caching objects, or when passing the object from one component to another. > -> An can be used to access external documents. The class helps to secure another implementation of by wrapping the object and restricting the resources that the underlying has access to. +> Use to restrict access to external documents. > > The and validation flags of an object are not set by default. When these flags are set, the of the object is used to resolve schema locations encountered in the instance document in the . If the object is `null`, schema locations are not resolved even if the and validation flags are set. > > Schemas added during validation add new types and can change the validation outcome of the document being validated. As a result, external schemas should only be resolved from trusted sources. -## Examples - The following example creates an that uses an with default credentials. - - :::code language="csharp" source="~/snippets/csharp/System.Xml/XmlParserContext/Overview/XmlReader_Create.cs" id="Snippet10"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Data/XmlReader.Create/VB/XmlReader_Create.vb" id="Snippet10"::: - ]]> diff --git a/xml/System.Xml/XmlResolver.xml b/xml/System.Xml/XmlResolver.xml index d2e87aabde0..4eec547c8e7 100644 --- a/xml/System.Xml/XmlResolver.xml +++ b/xml/System.Xml/XmlResolver.xml @@ -51,7 +51,51 @@ Resolves external XML resources named by a Uniform Resource Identifier (URI). - For more information about this API, see Supplemental API remarks for XmlResolver. + + type is used to resolve external XML resources, such as entities, document type definitions (DTDs), or schemas. It is also used to process include and import elements found in Extensible Stylesheet Language (XSL) style sheets or XML Schema definition language (XSD) schemas. + + handles all aspects of negotiating the connection to the resources, including handling security credentials, opening the connection to the data source, and returning the resource in the form of a stream or other object type. The object that calls has the task of interpreting the stream. + +The namespace includes the following concrete implementation of the class: + +- is the default resolver for all classes in the namespace. It supports the `file://` and `http://` protocols and requests from the class. For examples of extending the class to improve performance, see the reference page. + +You can create and specify your own resolver. If you don't specify a resolver, the reader uses a default with no user credentials. + +You specify the to use by setting the property and passing the object to the method. + +If the resource is stored on a system that requires authentication, you use the property to specify the necessary credentials. + +## Supply authentication credentials + +The file that contains the XML data to read may have a restricted access policy. If authentication is required to access a network resource, use the property to specify the necessary credentials. If the property is not set, credentials are set to `null`. + +For example, assume that credentials are needed when requesting data from the web for authentication purposes. Unless the web virtual directory allows anonymous access, you must set the property to supply credentials. The following example creates an object that uses an with default credentials to access the `http://localhost/bookstore/inventory.xml` site. + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlReader/Create/factory_rdr_cctor2.cs" id="Snippet2"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlResolver/Overview/factory_rdr_cctor2.vb" id="Snippet2"::: + +You can supply different credentials for different URIs and add them to a cache. These credentials are used to check authentication for the different URIs regardless of the original source of the XML. The following example shows how to add credentials to a cache. + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlResolver/Overview/Xslt_Load_v2.cs" id="Snippet11"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlResolver/Overview/Xslt_Load_v2.vb" id="Snippet11"::: + +## Security considerations + +Consider the following items when working with the class. + +- objects can contain sensitive information such as user credentials. You should be careful when caching objects and should not pass the object to an untrusted component. + +- If you are designing a class property that uses the class, the property should be defined as a write-only property. The property can be used to specify the to use, but it cannot be used to return an object. + +- If your application accepts objects from untrusted code, you cannot assume that the URI passed into the method will be the same as that returned by the method. Classes derived from the class can override the method and return data that is different than what was contained in the original URI. + +- Your application can mitigate memory denial of service threats to the method by implementing an that limits the number of bytes read. This helps guard against situations where malicious code attempts to pass an infinite stream of bytes to the method. + + ]]> + with default credentials. A is used to read and display the resulting data stream. diff --git a/xml/System.Xml/XmlSecureResolver.xml b/xml/System.Xml/XmlSecureResolver.xml index d5fa65d1ffe..c2e1340cd9e 100644 --- a/xml/System.Xml/XmlSecureResolver.xml +++ b/xml/System.Xml/XmlSecureResolver.xml @@ -55,7 +55,7 @@ Helps to secure another implementation of by wrapping the object and restricting the resources that the underlying has access to. - For more information about this API, see Supplemental API remarks for XmlSecureResolver. + To be added. diff --git a/xml/System.Xml/XmlTextReader.xml b/xml/System.Xml/XmlTextReader.xml index 4c6f62a46ab..ab9afe6c5a3 100644 --- a/xml/System.Xml/XmlTextReader.xml +++ b/xml/System.Xml/XmlTextReader.xml @@ -64,7 +64,60 @@ Represents a reader that provides fast, non-cached, forward-only access to XML data. We recommend that you use the class instead. - For more information about this API, see Supplemental API remarks for XmlTextReader. + + [!NOTE] +> We recommend that you create instances by using the method to take advantage of new functionality. + + provides forward-only, read-only access to a stream of XML data. The current node refers to the node on which the reader is positioned. The reader is advanced using any of the read methods and properties reflect the value of the current node. + +This class implements and conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations. `XmlTextReader` provides the following functionality: + +- Enforces the rules of well-formed XML. + +- `XmlTextReader` does not provide data validation. + +- Checks that `DocumentType` nodes are well-formed. `XmlTextReader` checks the DTD for well-formedness, but does not validate using the DTD. + +- For nodes where is `XmlNodeType.EntityReference`, a single empty `EntityReference` node is returned (that is, the property is `String.Empty`). + +> [!NOTE] +> The actual declarations of entities in the DTD are called `Entity` nodes. When you refer to these nodes in your data, they are called `EntityReference` nodes. + +- Does not expand default attributes. + +Because the `XmlTextReader` does not perform the extra checks required for data validation, it provides a fast well-formedness parser. + +To perform data validation, use a validating . + +To read XML data from an , use . + +`XmlTextReader` throws an on XML parse errors. After an exception is thrown the state of the reader is not predictable. For example, the reported node type may be different than the actual node type of the current node. Use the property to check whether a reader is in error state. + +## Security considerations + +The following are things to consider when using the class. + +- Exceptions thrown by the can disclose path information that you do not want bubbled up to the application. Your applications must catch exceptions and process them appropriately. + +- DTD processing is enabled by default. Disable DTD processing if you are concerned about Denial of Service issues or if you are dealing with untrusted sources. Set the property to to disable DTD processing. + + If you have DTD processing enabled, you can use to restrict the resources that the can access. You can also design your application so that the XML processing is memory and time constrained. For example, configure time-out limits in your ASP.NET application. + +- XML data can include references to external resources such as a DTD file. By default external resources are resolved using an object with no user credentials. You can secure this further by doing one of the following: + + - Restrict the resources that the can access by using . + - Do not allow the to open any external resources by setting the property to `null`. + +- XML data can contain a large number of attributes, namespace declarations, nested elements and so on that require a substantial amount of time to process. To limit the size of the input that is sent to the , create a custom IStream implementation and supply it the . + +- The method can be used to handle large streams of data. This method reads a small number of characters at a time instead of allocating a single string for the whole value. + +- By default general entities are not expanded. General entities are expanded when you call the method. + + ]]> + XML Documents and Data @@ -3532,7 +3585,7 @@ abc DTD processing is enabled by default for backwards compatibility. However, unless your application requires DTD processing, you should disable this setting. Disabling DTD processing can be useful in preventing certain denial of service attacks. If set to `true`, the reader throws an when any DTD content is encountered. - If you have DTD processing enabled, you need to be aware of including DTDs from untrusted sources and possible denial of service attacks. Use the to restrict the resources that the can access. You can also design your application so that the XML processing is memory and time constrained. For example, configure time-out limits in your ASP.NET application + If you have DTD processing enabled, you need to be aware of including DTDs from untrusted sources and possible denial of service attacks. Use to restrict the resources that the can access. You can also design your application so that the XML processing is memory and time constrained. For example, configure time-out limits in your ASP.NET application. ]]> @@ -5106,7 +5159,6 @@ if (XmlNodeType.Element == reader.NodeType && "thing" == reader.Name) - diff --git a/xml/System.Xml/XmlTextWriter.xml b/xml/System.Xml/XmlTextWriter.xml index afb34f759cb..aed3b8dcd0f 100644 --- a/xml/System.Xml/XmlTextWriter.xml +++ b/xml/System.Xml/XmlTextWriter.xml @@ -57,7 +57,112 @@ Represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations. We recommend that you use the class instead. - For more information about this API, see Supplemental API remarks for XmlTextWriter. + + class implements the class. + +> [!NOTE] +> We recommend that you create instances by using the method and the class to take advantage of new functionality. + +`XmlTextWriter` maintains a namespace stack corresponding to all the namespaces defined in the current element stack. Using `XmlTextWriter` you can declare namespaces manually. + +```csharp +w.WriteStartElement("root"); +w.WriteAttributeString("xmlns", "x", null, "urn:1"); +w.WriteStartElement("item","urn:1"); +w.WriteEndElement(); +w.WriteStartElement("item","urn:1"); +w.WriteEndElement(); +w.WriteEndElement(); +``` + +This C# code produces the following output. `XmlTextWriter` promotes the namespace declaration to the root element to avoid having it duplicated on the two child elements. The child elements pick up the prefix from the namespace declaration. + +```xml + + + + +``` + +`XmlTextWriter` also allows you to override the current namespace declaration. In the following example, the namespace URI "123" is overridden by "abc" to produce the XML element ``. + +```csharp +w.WriteStartElement("x","node","123"); +w.WriteAttributeString("xmlns","x",null,"abc"); +``` + +By using the write methods that take a prefix as an argument, you can also specify which prefix to use. In the following example, two different prefixes are mapped to the same namespace URI to produce the XML text ``. + +```csharp +XmlTextWriter w = new XmlTextWriter(Console.Out); +w.WriteStartElement("x","root","urn:1"); +w.WriteStartElement("y","item","urn:1"); +w.WriteEndElement(); +w.WriteEndElement(); +w.Close(); +``` + +If there are multiple namespace declarations mapping different prefixes to the same namespace URI, `XmlTextWriter` walks the stack of namespace declarations backwards and picks the closest one. + +```csharp +XmlTextWriter w = new XmlTextWriter(Console.Out); +w.Formatting = Formatting.Indented; +w.WriteStartElement("x","root","urn:1"); +w.WriteStartElement("y","item","urn:1"); +w.WriteAttributeString("attr","urn:1","123"); +w.WriteEndElement(); +w.WriteEndElement(); +w.Close(); +``` + +In this C# example, because the `WriteAttributeString` call does not specify a prefix, the writer uses the last prefix pushed onto the namespace stack, and produces the following XML: + +```xml + + + +``` + +If namespace conflicts occur, `XmlTextWriter` resolves them by generating alternate prefixes. For example, if an attribute and element have the same prefix but different namespaces, `XmlWriter` generates an alternate prefix for the attribute. The generated prefixes are named `n{i}` where `i` is a number beginning at 1. The number is reset to 1 for each element. + +Attributes which are associated with a namespace URI must have a prefix (default namespaces do not apply to attributes). This conforms to section 5.2 of the W3C Namespaces in XML recommendation. If an attribute references a namespace URI, but does not specify a prefix, the writer generates a prefix for the attribute. + +When writing an empty element, an additional space is added between tag name and the closing tag, for example ``. This provides compatibility with older browsers. + +When a `String` is used as method parameter, `null` and `String.Empty` are equivalent. `String.Empty` follows the W3C rules. + +To write strongly typed data, use the class to convert data types to string. For example, the following C# code converts the data from `Double` to `String` and writes the element `19.95`. + +```csharp +Double price = 19.95; +writer.WriteElementString("price", XmlConvert.ToString(price)); +``` + +`XmlTextWriter` does not check for the following: + +- Invalid characters in attribute and element names. +- Unicode characters that do not fit the specified encoding. If the Unicode characters do not fit the specified encoding, the `XmlTextWriter` does not escape the Unicode characters into character entities. +- Duplicate attributes. +- Characters in the DOCTYPE public identifier or system identifier. + +## Security considerations + +The following items are things to consider when working with the class. + +- Exceptions thrown by the can disclose path information that you do not want bubbled up to the application. Your applications must catch exceptions and process them appropriately. + +- When you pass the to another application the underlying stream is exposed to that application. If you need to pass the to a semi-trusted application, you should use an object created by the method instead. + +- The does not validate any data that is passed to the or methods. You should not pass arbitrary data to these methods. + +- If the default settings are changed, there is no guarantee that the generated output is well-formed XML data. + +- Do not accept supporting components, such as an object, from an untrusted source. + + ]]> + XML Documents and Data
@@ -1932,7 +2037,7 @@ writer.WriteStartElement("root"); ```xml - + ``` If `ns` maps to the current default namespace, no prefix is generated. diff --git a/xml/System.Xml/XmlValidatingReader.xml b/xml/System.Xml/XmlValidatingReader.xml index 24ff9f5d6d1..ffad491425a 100644 --- a/xml/System.Xml/XmlValidatingReader.xml +++ b/xml/System.Xml/XmlValidatingReader.xml @@ -2832,7 +2832,6 @@ - diff --git a/xml/System.Xml/XmlWriter.xml b/xml/System.Xml/XmlWriter.xml index 6b636262345..7a0c7d1f6af 100644 --- a/xml/System.Xml/XmlWriter.xml +++ b/xml/System.Xml/XmlWriter.xml @@ -66,7 +66,135 @@ Represents a writer that provides a fast, non-cached, forward-only way to generate streams or files that contain XML data. - For more information about this API, see Supplemental API remarks for XmlWriter. + + class writes XML data to a stream, file, text, or string. It supports the W3C [Extensible Markup Language (XML) 1.0 (fourth edition)](https://www.w3.org/TR/2006/REC-xml-20060816/) and [Namespaces in XML 1.0 (third edition)](https://www.w3.org/TR/REC-xml-names/) recommendations. + +The members of the class enable you to: + +- Verify that the characters are legal XML characters and that element and attribute names are valid XML names. +- Verify that the XML document is well-formed. +- Encode binary bytes as Base64 or BinHex, and write out the resulting text. +- Pass values by using common language runtime types instead of strings, to avoid having to manually perform value conversions. +- Write multiple documents to one output stream. +- Write valid names, qualified names, and name tokens. + +## Create an XML writer + +To create an instance, use the method. To specify the set of features you want to enable on the XML writer, pass an to the method. Otherwise, default settings are used. See the reference pages for details. + +## Specify the output format + +The class includes several properties that control how output is formatted: + +|Property|Description| +|--------------|-----------------| +||Specifies the text encoding to use. The default is `Encoding.UTF8`.| +||Indicates whether to indent elements. The default is `false` (no indentation).| +||Specifies the character string to use when indenting. The default is two spaces.| +||Specifies the character string to use for line breaks. The default is `\r\n` (carriage return, line feed) for non-Unix platforms, and `\n` (line feed) for Unix platforms.| +||Specifies how to handle newline characters.| +||Indicates whether to write attributes on a new line. should be set to `true` when using this property. The default is `false`.| +||Indicates whether to write an XML declaration. The default is `false`.| + +The and properties control how insignificant white space is formatted. For example, to indent element nodes: + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlWriter/Overview/writer_v2.cs" id="Snippet8"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlWriter/Overview/writer_v2.vb" id="Snippet8"::: + +Use the to write each attribute on a new line with one extra level of indentation: + +:::code language="csharp" source="~/snippets/csharp/System.Xml/XmlWriter/Overview/writer_v2.cs" id="Snippet9"::: +:::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlWriter/Overview/writer_v2.vb" id="Snippet9"::: + +## Data conformance + +An XML writer uses two properties from the class to check for data conformance: + +- The property instructs the XML writer to check characters and throw an exception if any characters are outside the legal range, as defined by the W3C. + +- The property configures the XML writer to check that the stream being written complies with the rules for a well-formed XML 1.0 document or document fragment, as defined by the W3C. The three conformance levels are described in the following table. The default is . For details, see the property and the enumeration. + + |Level|Description| + |-----------|-----------------| + ||The XML output conforms to the rules for a well-formed XML 1.0 document and can be processed by any conforming processor.| + ||The XML output conforms to the rules for a well-formed XML 1.0 document fragment.| + ||The XML writer determines which level of conformation checking to apply (document or fragment) based on the incoming data.| + +## Write elements + +You can use the following methods to write element nodes. For examples, see the methods listed. + +|Use|To| +|---------|--------| +||Write an entire element node, including a string value.| +||To write an element value by using multiple method calls. For example, you can call to write a typed value, to write a character entity, to write an attribute, or you can write a child element. This is a more sophisticated version of the method.

To close the element, you call the or method.| +||To copy an element node found at the current position of an or object. When called, it copies everything from the source object to the instance.| + +## Write attributes + +You can use the following methods to write attributes on element nodes. These methods can also be used to create namespace declarations on an element, as discussed in the next section. + +|Use|To| +|---------|--------| +||To write an entire attribute node, including a string value.| +||To write the attribute value using multiple method calls. For example, you can call to write a typed value. This is a more sophisticated version of the method.

To close the element, you call the method.| +||To copy all the attributes found at the current position of an object. The attributes that are written depend on the type of node the reader is currently positioned on:

- For an attribute node, it writes the current attribute, and then the rest of the attributes until the element closing tag.
- For an element node, it writes all attributes contained by the element.
- For an XML declaration node, it writes all the attributes in the declaration.
- For all other node types, the method throws an exception.| + +## Handle namespaces + +Namespaces are used to qualify element and attribute names in an XML document. Namespace prefixes associate elements and attributes with namespaces, which are in turn associated with URI references. Namespaces create element and attribute name uniqueness in an XML document. + +The maintains a namespace stack that corresponds to all the namespaces defined in the current namespace scope. When writing elements and attributes you can utilize namespaces in the following ways: + +- Declare namespaces manually by using the method. This can be useful when you know how to best optimize the number of namespace declarations. For an example, see the method. + +- Override the current namespace declaration with a new namespace. In the following code, the method changes the namespace URI for the `"x"` prefix from `"123"` to `"abc"`. + + :::code language="csharp" source="~/snippets/csharp/System.Xml/XmlWriter/Overview/writer_v2.cs" id="Snippet18"::: + :::code language="vb" source="~/snippets/visualbasic/System.Xml/XmlWriter/Overview/writer_v2.vb" id="Snippet18"::: + + The code generates the following XML string: + + ```xml + + + + ``` + +- Specify a namespace prefix when writing attributes or elements. Many of the methods used to write element and attributes enable you to do this. For example, the method writes a start tag and associates it with a specified namespace and prefix. + +## Write typed data + +The method accepts a common language runtime (CLR) object, converts the input value to its string representation according to XML schema definition language (XSD) data type conversion rules, and writes it out by using the method. This is easier than using the methods in the class to convert the typed data to a string value before writing it out. + +When writing to text, the typed value is serialized to text by using the rules for that schema type. + +For default XSD data types that correspond to CLR types, see the method. + +The can also be used to write to an XML data store. For example, the class can create an object to create nodes for an object. If the data store has schema information available to it, the method throws an exception if you try to convert to a type that is not allowed. If the data store does not have schema information available to it, the method treats all values as an `xsd:anySimpleType` type. + +## Close the XML writer + +When you use methods to output XML, the elements and attributes are not written until you call the method. For example, if you are using to populate an object, you won't be able to see the written elements and attributes in the target document until you close the instance. + +## Asynchronous programming + +Most of the methods have asynchronous counterparts that have "Async" at the end of their method names. For example, the asynchronous equivalent of is . + +For the method, which doesn't have an asynchronous counterpart, convert the return value to a string and use the method instead. + +## Security considerations + +Consider the following when working with the class: + +- Exceptions thrown by the can disclose path information that you do not want bubbled up to the app. Your app must catch exceptions and process them appropriately. + +- does not validate any data that is passed to the or method. You should not pass arbitrary data to these methods. + + ]]>
+
The following example code shows how to use the asynchronous API to generate XML.