private void RemoveDuplicateNamespace(XmlElement elem, XmlNamespaceManager mgr, bool fCheckElemAttrs) { mgr.PushScope(); XmlAttributeCollection attributes = elem.Attributes; int count = attributes.Count; if (fCheckElemAttrs && (count > 0)) { for (int i = count - 1; i >= 0; i--) { XmlAttribute attribute = attributes[i]; if (attribute.Prefix == this.doc.strXmlns) { string str = mgr.LookupNamespace(attribute.LocalName); if (str == null) { mgr.AddNamespace(attribute.LocalName, attribute.Value); } else if (attribute.Value == str) { elem.Attributes.RemoveNodeAt(i); } } else if ((attribute.Prefix.Length == 0) && (attribute.LocalName == this.doc.strXmlns)) { string defaultNamespace = mgr.DefaultNamespace; if (defaultNamespace != null) { if (attribute.Value == defaultNamespace) { elem.Attributes.RemoveNodeAt(i); } } else { mgr.AddNamespace(attribute.LocalName, attribute.Value); } } } } for (XmlNode node = elem.FirstChild; node != null; node = node.NextSibling) { XmlElement element = node as XmlElement; if (element != null) { this.RemoveDuplicateNamespace(element, mgr, true); } } mgr.PopScope(); }
public override bool Read() { switch (state) { case State.Initial: useCurNode = false; state = State.Interactive; ProcessNamespaces(); return(true); case State.Interactive: curNsAttr = -1; useCurNode = false; reader.MoveToElement(); Debug.Assert(reader.Depth >= initialDepth); if (reader.Depth == initialDepth) { if (reader.NodeType == XmlNodeType.EndElement || (reader.NodeType == XmlNodeType.Element && reader.IsEmptyElement)) { state = State.EndOfFile; SetEmptyNode(); return(false); } Debug.Assert(reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement); } if (reader.Read()) { ProcessNamespaces(); return(true); } else { SetEmptyNode(); return(false); } case State.EndOfFile: case State.Closed: return(false); case State.PopNamespaceScope: nsManager.PopScope(); goto case State.ClearNsAttributes; case State.ClearNsAttributes: nsAttrCount = 0; state = State.Interactive; goto case State.Interactive; case State.ReadElementContentAsBase64: case State.ReadElementContentAsBinHex: if (!FinishReadElementContentAsBinary()) { return(false); } return(Read()); case State.ReadContentAsBase64: case State.ReadContentAsBinHex: if (!FinishReadContentAsBinary()) { return(false); } return(Read()); default: Debug.Assert(false); return(false); } }
private void ValidateElement() { _nsManager.PushScope(); XmlElement elementNode = _currentNode as XmlElement; Debug.Assert(elementNode != null); XmlAttributeCollection attributes = elementNode.Attributes; XmlAttribute attr = null; //Find Xsi attributes that need to be processed before validating the element string xsiNil = null; string xsiType = null; for (int i = 0; i < attributes.Count; i++) { attr = attributes[i]; string objectNs = attr.NamespaceURI; string objectName = attr.LocalName; Debug.Assert(_nameTable.Get(attr.NamespaceURI) != null); Debug.Assert(_nameTable.Get(attr.LocalName) != null); if (Ref.Equal(objectNs, _nsXsi)) { if (Ref.Equal(objectName, _xsiType)) { xsiType = attr.Value; } else if (Ref.Equal(objectName, _xsiNil)) { xsiNil = attr.Value; } } else if (Ref.Equal(objectNs, _nsXmlNs)) { _nsManager.AddNamespace(attr.Prefix.Length == 0 ? string.Empty : attr.LocalName, attr.Value); } } _validator.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, _schemaInfo, xsiType, xsiNil, null, null); ValidateAttributes(elementNode); _validator.ValidateEndOfAttributes(_schemaInfo); //If element has children, drill down for (XmlNode child = elementNode.FirstChild; child != null; child = child.NextSibling) { ValidateNode(child); } //Validate end of element _currentNode = elementNode; //Reset current Node for validation call back _validator.ValidateEndElement(_schemaInfo); //Get XmlName, as memberType / validity might be set now if (_psviAugmentation) { elementNode.XmlName = _document.AddXmlName(elementNode.Prefix, elementNode.LocalName, elementNode.NamespaceURI, _schemaInfo); if (_schemaInfo.IsDefault) { //the element has a default value XmlText textNode = _document.CreateTextNode(_schemaInfo.SchemaElement.ElementDecl.DefaultValueRaw); elementNode.AppendChild(textNode); } } _nsManager.PopScope(); //Pop current namespace scope }
private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) { if (string.IsNullOrEmpty(propertyName)) throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML."); Dictionary<string, string> dictionary = this.ReadAttributeElements(reader, manager); string prefix1 = MiscellaneousUtils.GetPrefix(propertyName); if (propertyName.StartsWith("@")) { string str1 = propertyName.Substring(1); string str2 = reader.Value.ToString(); string prefix2 = MiscellaneousUtils.GetPrefix(str1); IXmlNode attribute = !string.IsNullOrEmpty(prefix2) ? document.CreateAttribute(str1, manager.LookupNamespace(prefix2), str2) : document.CreateAttribute(str1, str2); ((IXmlElement) currentNode).SetAttributeNode(attribute); } else { IXmlElement element = this.CreateElement(propertyName, document, prefix1, manager); currentNode.AppendChild((IXmlNode) element); foreach (KeyValuePair<string, string> keyValuePair in dictionary) { string prefix2 = MiscellaneousUtils.GetPrefix(keyValuePair.Key); IXmlNode attribute = !string.IsNullOrEmpty(prefix2) ? document.CreateAttribute(keyValuePair.Key, manager.LookupNamespace(prefix2), keyValuePair.Value) : document.CreateAttribute(keyValuePair.Key, keyValuePair.Value); element.SetAttributeNode(attribute); } if (reader.TokenType == JsonToken.String || reader.TokenType == JsonToken.Integer || (reader.TokenType == JsonToken.Float || reader.TokenType == JsonToken.Boolean) || reader.TokenType == JsonToken.Date) { element.AppendChild(document.CreateTextNode(this.ConvertTokenToXmlValue(reader))); } else { if (reader.TokenType == JsonToken.Null || reader.TokenType == JsonToken.EndObject) return; manager.PushScope(); this.DeserializeNode(reader, document, manager, (IXmlNode) element); manager.PopScope(); } } }
public void XmlSchemaValidatorDoesNotEnforceIdentityConstraintsOnDefaultAttributesInSomeCases() { Initialize(); string xml = @"<?xml version='1.0'?> <root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='idF016.xsd'> <uid val='test'/> <uid/></root>"; string xsd = @"<?xml version='1.0'?> <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' elementFormDefault='qualified'> <xsd:element name='root'> <xsd:complexType> <xsd:sequence> <xsd:element ref='uid' maxOccurs='unbounded'/> </xsd:sequence> </xsd:complexType> <xsd:unique id='foo123' name='uuid'> <xsd:selector xpath='.//uid'/> <xsd:field xpath='@val'/> </xsd:unique> </xsd:element> <xsd:element name='uid' nillable='true'> <xsd:complexType> <xsd:attribute name='val' type='xsd:string' default='test'/> </xsd:complexType> </xsd:element> </xsd:schema>"; XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable()); XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add(null, XmlReader.Create(new StringReader(xsd))); schemas.Compile(); XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.AllowXmlAttributes; XmlSchemaValidator validator = new XmlSchemaValidator(namespaceManager.NameTable, schemas, namespaceManager, validationFlags); validator.Initialize(); using (XmlReader r = XmlReader.Create(new StringReader(xsd))) { while (r.Read()) { switch (r.NodeType) { case XmlNodeType.Element: namespaceManager.PushScope(); if (r.MoveToFirstAttribute()) { do { if (r.NamespaceURI == "http://www.w3.org/2000/xmlns/") { namespaceManager.AddNamespace(r.LocalName, r.Value); } } while (r.MoveToNextAttribute()); r.MoveToElement(); } validator.ValidateElement(r.LocalName, r.NamespaceURI, null, null, null, null, null); if (r.MoveToFirstAttribute()) { do { if (r.NamespaceURI != "http://www.w3.org/2000/xmlns/") { validator.ValidateAttribute(r.LocalName, r.NamespaceURI, r.Value, null); } } while (r.MoveToNextAttribute()); r.MoveToElement(); } validator.ValidateEndOfAttributes(null); if (r.IsEmptyElement) goto case XmlNodeType.EndElement; break; case XmlNodeType.EndElement: validator.ValidateEndElement(null); namespaceManager.PopScope(); break; case XmlNodeType.Text: validator.ValidateText(r.Value); break; case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: validator.ValidateWhitespace(r.Value); break; default: break; } } validator.EndValidation(); } XmlReaderSettings rs = new XmlReaderSettings(); rs.ValidationType = ValidationType.Schema; rs.Schemas.Add(null, XmlReader.Create(new StringReader(xsd))); using (XmlReader r = XmlReader.Create(new StringReader(xml), rs)) { try { while (r.Read()) ; } catch (XmlSchemaValidationException e) { _output.WriteLine(e.Message); return; } } Assert.True(false); }
private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) { if (string.IsNullOrEmpty(propertyName)) throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML."); Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager); string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); if (propertyName.StartsWith("@")) { var attributeName = propertyName.Substring(1); var attributeValue = reader.Value.ToString(); var attributePrefix = MiscellaneousUtils.GetPrefix(attributeName); var attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(attributeName, manager.LookupNamespace(attributePrefix), attributeValue) : document.CreateAttribute(attributeName, attributeValue); ((IXmlElement)currentNode).SetAttributeNode(attribute); } else { IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager); currentNode.AppendChild(element); // add attributes to newly created element foreach (KeyValuePair<string, string> nameValue in attributeNameValues) { string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix), nameValue.Value) : document.CreateAttribute(nameValue.Key, nameValue.Value); element.SetAttributeNode(attribute); } if (reader.TokenType == JsonToken.String || reader.TokenType == JsonToken.Integer || reader.TokenType == JsonToken.Float || reader.TokenType == JsonToken.Boolean || reader.TokenType == JsonToken.Date) { element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader))); } else if (reader.TokenType == JsonToken.Null) { // empty element. do nothing } else { // finished element will have no children to deserialize if (reader.TokenType != JsonToken.EndObject) { manager.PushScope(); DeserializeNode(reader, document, manager, element); manager.PopScope(); } } } }
public void AddPushPopRemove () { XmlNamespaceManager nsmgr = new XmlNamespaceManager (new NameTable ()); string ns = nsmgr.NameTable.Add ("urn:foo"); nsmgr.AddNamespace ("foo", ns); Assert.AreEqual ("foo", nsmgr.LookupPrefix (ns)); nsmgr.PushScope (); Assert.AreEqual ("foo", nsmgr.LookupPrefix (ns)); nsmgr.PopScope (); Assert.AreEqual ("foo", nsmgr.LookupPrefix (ns)); nsmgr.RemoveNamespace ("foo", ns); Assert.IsNull (nsmgr.LookupPrefix (ns)); }
// Note that this must be done *before* filtering nodes out // by context node list. private void FillMissingPrefixes (XmlNode n, XmlNamespaceManager nsmgr, ArrayList tmpList) { if (n.Prefix.Length == 0 && propagatedNss != null) { foreach (DictionaryEntry de in propagatedNss) if ((string) de.Value == n.NamespaceURI) { n.Prefix = (string) de.Key; break; } } if (n.NodeType == XmlNodeType.Element && ((XmlElement) n).HasAttributes) { foreach (XmlAttribute a in n.Attributes) if (a.NamespaceURI == "http://www.w3.org/2000/xmlns/") nsmgr.AddNamespace (a.Prefix.Length == 0 ? String.Empty : a.LocalName, a.Value); nsmgr.PushScope (); } if (n.NamespaceURI.Length > 0 && nsmgr.LookupPrefix (n.NamespaceURI) == null) tmpList.Add (CreateXmlns (n)); if (n.NodeType == XmlNodeType.Element && ((XmlElement) n).HasAttributes) { foreach (XmlAttribute a in n.Attributes) if (a.NamespaceURI.Length > 0 && nsmgr.LookupNamespace (a.Prefix) == null) tmpList.Add (CreateXmlns (a)); } foreach (XmlAttribute a in tmpList) ((XmlElement) n).SetAttributeNode (a); tmpList.Clear (); if (n.HasChildNodes) { for (XmlNode c = n.FirstChild; c != null; c = c.NextSibling) if (c.NodeType == XmlNodeType.Element) FillMissingPrefixes (c, nsmgr, tmpList); } nsmgr.PopScope (); }
public void GetNamespacesInScope () { XmlNamespaceManager nsmgr = new XmlNamespaceManager (new NameTable ()); AssertEquals (0, nsmgr.GetNamespacesInScope (l).Count); AssertEquals (0, nsmgr.GetNamespacesInScope (x).Count); AssertEquals (1, nsmgr.GetNamespacesInScope (a).Count); nsmgr.AddNamespace ("foo", "urn:foo"); AssertEquals (1, nsmgr.GetNamespacesInScope (l).Count); AssertEquals (1, nsmgr.GetNamespacesInScope (x).Count); AssertEquals (2, nsmgr.GetNamespacesInScope (a).Count); // default namespace nsmgr.AddNamespace ("", "urn:empty"); AssertEquals (1, nsmgr.GetNamespacesInScope (l).Count); AssertEquals (1, nsmgr.GetNamespacesInScope (x).Count); AssertEquals (2, nsmgr.GetNamespacesInScope (a).Count); // PushScope nsmgr.AddNamespace ("foo", "urn:foo"); nsmgr.PushScope (); AssertEquals (0, nsmgr.GetNamespacesInScope (l).Count); AssertEquals (1, nsmgr.GetNamespacesInScope (x).Count); AssertEquals (2, nsmgr.GetNamespacesInScope (a).Count); // PopScope nsmgr.PopScope (); AssertEquals (1, nsmgr.GetNamespacesInScope (l).Count); AssertEquals (1, nsmgr.GetNamespacesInScope (x).Count); AssertEquals (2, nsmgr.GetNamespacesInScope (a).Count); nsmgr.AddNamespace ("", ""); AssertEquals (1, nsmgr.GetNamespacesInScope (l).Count); AssertEquals (1, nsmgr.GetNamespacesInScope (x).Count); AssertEquals (2, nsmgr.GetNamespacesInScope (a).Count); }
public void PopScopeMustKeepAddedInScope () { namespaceManager = new XmlNamespaceManager (new NameTable ()); // clear namespaceManager .AddNamespace ("foo", "urn:foo"); // 0 namespaceManager .AddNamespace ("bar", "urn:bar"); // 0 namespaceManager .PushScope (); // 1 namespaceManager .PushScope (); // 2 namespaceManager .PopScope (); // 2 namespaceManager .PopScope (); // 1 namespaceManager .PopScope (); // 0 Assert.AreEqual ("urn:foo", namespaceManager.LookupNamespace ("foo")); Assert.AreEqual ("urn:bar", namespaceManager.LookupNamespace ("bar")); }
// Token: 0x060006E1 RID: 1761 // RVA: 0x00037C10 File Offset: 0x00035E10 private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) { switch (node.NodeType) { case XmlNodeType.Element: if (this.IsArray(node)) { if (Enumerable.All<IXmlNode>(node.ChildNodes, (IXmlNode n) => n.LocalName == node.LocalName) && node.ChildNodes.Count > 0) { this.SerializeGroupedNodes(writer, node, manager, false); return; } } manager.PushScope(); foreach (IXmlNode current in node.Attributes) { if (current.NamespaceUri == "http://www.w3.org/2000/xmlns/") { string prefix = (current.LocalName != "xmlns") ? current.LocalName : string.Empty; string value = current.Value; manager.AddNamespace(prefix, value); } } if (writePropertyName) { writer.WritePropertyName(this.GetPropertyName(node, manager)); } if (!Enumerable.Any<IXmlNode>(this.ValueAttributes(node.Attributes)) && node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType == XmlNodeType.Text) { writer.WriteValue(node.ChildNodes[0].Value); } else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty<IXmlNode>(node.Attributes)) { IXmlElement xmlElement = (IXmlElement)node; if (xmlElement.IsEmpty) { writer.WriteNull(); } else { writer.WriteValue(string.Empty); } } else { writer.WriteStartObject(); for (int i = 0; i < node.Attributes.Count; i++) { this.SerializeNode(writer, node.Attributes[i], manager, true); } this.SerializeGroupedNodes(writer, node, manager, true); writer.WriteEndObject(); } manager.PopScope(); return; case XmlNodeType.Attribute: case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.ProcessingInstruction: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if (node.NamespaceUri == "http://www.w3.org/2000/xmlns/" && node.Value == "http://james.newtonking.com/projects/json") { return; } if (node.NamespaceUri == "http://james.newtonking.com/projects/json" && node.LocalName == "Array") { return; } if (writePropertyName) { writer.WritePropertyName(this.GetPropertyName(node, manager)); } writer.WriteValue(node.Value); return; case XmlNodeType.Comment: if (writePropertyName) { writer.WriteComment(node.Value); return; } return; case XmlNodeType.Document: case XmlNodeType.DocumentFragment: this.SerializeGroupedNodes(writer, node, manager, writePropertyName); return; case XmlNodeType.DocumentType: { IXmlDocumentType xmlDocumentType = (IXmlDocumentType)node; writer.WritePropertyName(this.GetPropertyName(node, manager)); writer.WriteStartObject(); if (!string.IsNullOrEmpty(xmlDocumentType.Name)) { writer.WritePropertyName("@name"); writer.WriteValue(xmlDocumentType.Name); } if (!string.IsNullOrEmpty(xmlDocumentType.Public)) { writer.WritePropertyName("@public"); writer.WriteValue(xmlDocumentType.Public); } if (!string.IsNullOrEmpty(xmlDocumentType.System)) { writer.WritePropertyName("@system"); writer.WriteValue(xmlDocumentType.System); } if (!string.IsNullOrEmpty(xmlDocumentType.InternalSubset)) { writer.WritePropertyName("@internalSubset"); writer.WriteValue(xmlDocumentType.InternalSubset); } writer.WriteEndObject(); return; } case XmlNodeType.XmlDeclaration: { IXmlDeclaration xmlDeclaration = (IXmlDeclaration)node; writer.WritePropertyName(this.GetPropertyName(node, manager)); writer.WriteStartObject(); if (!string.IsNullOrEmpty(xmlDeclaration.Version)) { writer.WritePropertyName("@version"); writer.WriteValue(xmlDeclaration.Version); } if (!string.IsNullOrEmpty(xmlDeclaration.Encoding)) { writer.WritePropertyName("@encoding"); writer.WriteValue(xmlDeclaration.Encoding); } if (!string.IsNullOrEmpty(xmlDeclaration.Standalone)) { writer.WritePropertyName("@standalone"); writer.WriteValue(xmlDeclaration.Standalone); } writer.WriteEndObject(); return; } } throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType); }
// Token: 0x060006E4 RID: 1764 // RVA: 0x000382C8 File Offset: 0x000364C8 private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) { if (string.IsNullOrEmpty(propertyName)) { throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML."); } Dictionary<string, string> dictionary = this.ReadAttributeElements(reader, manager); string prefix = MiscellaneousUtils.GetPrefix(propertyName); if (StringUtils.StartsWith(propertyName, '@')) { string text = propertyName.Substring(1); string value = reader.Value.ToString(); string prefix2 = MiscellaneousUtils.GetPrefix(text); IXmlNode attributeNode = (!string.IsNullOrEmpty(prefix2)) ? document.CreateAttribute(text, manager.LookupNamespace(prefix2), value) : document.CreateAttribute(text, value); ((IXmlElement)currentNode).SetAttributeNode(attributeNode); return; } IXmlElement xmlElement = this.CreateElement(propertyName, document, prefix, manager); currentNode.AppendChild(xmlElement); foreach (KeyValuePair<string, string> current in dictionary) { string prefix3 = MiscellaneousUtils.GetPrefix(current.Key); IXmlNode attributeNode2 = (!string.IsNullOrEmpty(prefix3)) ? document.CreateAttribute(current.Key, manager.LookupNamespace(prefix3), current.Value) : document.CreateAttribute(current.Key, current.Value); xmlElement.SetAttributeNode(attributeNode2); } if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Integer && reader.TokenType != JsonToken.Float && reader.TokenType != JsonToken.Boolean) { if (reader.TokenType != JsonToken.Date) { if (reader.TokenType == JsonToken.Null) { return; } if (reader.TokenType != JsonToken.EndObject) { manager.PushScope(); this.DeserializeNode(reader, document, manager, xmlElement); manager.PopScope(); } manager.RemoveNamespace(string.Empty, manager.DefaultNamespace); return; } } xmlElement.AppendChild(document.CreateTextNode(this.ConvertTokenToXmlValue(reader))); }
private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) { switch (node.NodeType) { case XmlNodeType.Document: case XmlNodeType.DocumentFragment: SerializeGroupedNodes(writer, node, manager, writePropertyName); break; case XmlNodeType.Element: if (IsArray(node) && node.ChildNodes.All(n => n.LocalName == node.LocalName) && node.ChildNodes.Count > 0) { SerializeGroupedNodes(writer, node, manager, false); } else { manager.PushScope(); foreach (IXmlNode attribute in node.Attributes) { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/") { string namespacePrefix = (attribute.LocalName != "xmlns") ? attribute.LocalName : string.Empty; string namespaceUri = attribute.Value; manager.AddNamespace(namespacePrefix, namespaceUri); } } if (writePropertyName) writer.WritePropertyName(GetPropertyName(node, manager)); if (!ValueAttributes(node.Attributes).Any() && node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType == XmlNodeType.Text) { // write elements with a single text child as a name value pair writer.WriteValue(node.ChildNodes[0].Value); } else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes)) { IXmlElement element = (IXmlElement)node; // empty element if (element.IsEmpty) writer.WriteNull(); else writer.WriteValue(string.Empty); } else { writer.WriteStartObject(); for (int i = 0; i < node.Attributes.Count; i++) { SerializeNode(writer, node.Attributes[i], manager, true); } SerializeGroupedNodes(writer, node, manager, true); writer.WriteEndObject(); } manager.PopScope(); } break; case XmlNodeType.Comment: if (writePropertyName) writer.WriteComment(node.Value); break; case XmlNodeType.Attribute: case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.ProcessingInstruction: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if (node.NamespaceUri == "http://www.w3.org/2000/xmlns/" && node.Value == JsonNamespaceUri) return; if (node.NamespaceUri == JsonNamespaceUri) { if (node.LocalName == "Array") return; } if (writePropertyName) writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteValue(node.Value); break; case XmlNodeType.XmlDeclaration: IXmlDeclaration declaration = (IXmlDeclaration)node; writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteStartObject(); if (!string.IsNullOrEmpty(declaration.Version)) { writer.WritePropertyName("@version"); writer.WriteValue(declaration.Version); } if (!string.IsNullOrEmpty(declaration.Encoding)) { writer.WritePropertyName("@encoding"); writer.WriteValue(declaration.Encoding); } if (!string.IsNullOrEmpty(declaration.Standalone)) { writer.WritePropertyName("@standalone"); writer.WriteValue(declaration.Standalone); } writer.WriteEndObject(); break; case XmlNodeType.DocumentType: IXmlDocumentType documentType = (IXmlDocumentType)node; writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteStartObject(); if (!string.IsNullOrEmpty(documentType.Name)) { writer.WritePropertyName("@name"); writer.WriteValue(documentType.Name); } if (!string.IsNullOrEmpty(documentType.Public)) { writer.WritePropertyName("@public"); writer.WriteValue(documentType.Public); } if (!string.IsNullOrEmpty(documentType.System)) { writer.WritePropertyName("@system"); writer.WriteValue(documentType.System); } if (!string.IsNullOrEmpty(documentType.InternalSubset)) { writer.WritePropertyName("@internalSubset"); writer.WriteValue(documentType.InternalSubset); } writer.WriteEndObject(); break; default: throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType); } }
public void GetNamespacesInScope () { XmlNamespaceManager nsmgr = new XmlNamespaceManager (new NameTable ()); Assert.AreEqual (0, nsmgr.GetNamespacesInScope (l).Count, "#1"); Assert.AreEqual (0, nsmgr.GetNamespacesInScope (x).Count, "#2"); Assert.AreEqual (1, nsmgr.GetNamespacesInScope (a).Count, "#3"); nsmgr.AddNamespace ("foo", "urn:foo"); Assert.AreEqual (1, nsmgr.GetNamespacesInScope (l).Count, "#4"); Assert.AreEqual (1, nsmgr.GetNamespacesInScope (x).Count, "#5"); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (a).Count, "#6"); // default namespace nsmgr.AddNamespace ("", "urn:empty"); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (l).Count, "#7"); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (x).Count, "#8"); Assert.AreEqual (3, nsmgr.GetNamespacesInScope (a).Count, "#9"); // PushScope nsmgr.AddNamespace ("foo", "urn:foo"); nsmgr.PushScope (); Assert.AreEqual (0, nsmgr.GetNamespacesInScope (l).Count, "#10"); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (x).Count, "#11"); Assert.AreEqual (3, nsmgr.GetNamespacesInScope (a).Count, "#12"); // PopScope nsmgr.PopScope (); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (l).Count, "#13"); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (x).Count, "#14"); Assert.AreEqual (3, nsmgr.GetNamespacesInScope (a).Count, "#15"); nsmgr.AddNamespace ("", ""); // MS bug - it should return 1 for .Local but it returns 2 instead. //Assert.AreEqual (1, nsmgr.GetNamespacesInScope (l).Count, "#16"); Assert.AreEqual (1, nsmgr.GetNamespacesInScope (x).Count, "#17"); Assert.AreEqual (2, nsmgr.GetNamespacesInScope (a).Count, "#18"); }
private void RemoveDuplicateNamespace(XmlElement elem, XmlNamespaceManager mgr, bool fCheckElemAttrs) { //remove the duplicate attributes on current node first mgr.PushScope(); XmlAttributeCollection attrs = elem.Attributes; int cAttrs = attrs.Count; if (fCheckElemAttrs && cAttrs > 0) { for (int i = cAttrs - 1; i >= 0; --i) { XmlAttribute attr = attrs[i]; if (attr.Prefix == _doc.strXmlns) { string nsUri = mgr.LookupNamespace(attr.LocalName); if (nsUri != null) { if (attr.Value == nsUri) elem.Attributes.RemoveNodeAt(i); } else { // Add this namespace, so it we will behave correctly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as // InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>" // If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for // the subsequent InnerXml_set or setting an EntRef inside. mgr.AddNamespace(attr.LocalName, attr.Value); } } else if (attr.Prefix.Length == 0 && attr.LocalName == _doc.strXmlns) { string nsUri = mgr.DefaultNamespace; if (nsUri != null) { if (attr.Value == nsUri) elem.Attributes.RemoveNodeAt(i); } else { // Add this namespace, so it we will behave correctly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as // InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>" // If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for // the subsequent InnerXml_set or setting an EntRef inside. mgr.AddNamespace(attr.LocalName, attr.Value); } } } } //now recursively remove the duplicate attributes on the children XmlNode child = elem.FirstChild; while (child != null) { XmlElement childElem = child as XmlElement; if (childElem != null) RemoveDuplicateNamespace(childElem, mgr, true); child = child.NextSibling; } mgr.PopScope(); }
private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) { Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager); string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager); currentNode.AppendChild(element); // add attributes to newly created element foreach (KeyValuePair<string, string> nameValue in attributeNameValues) { string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix), nameValue.Value) : document.CreateAttribute(nameValue.Key, nameValue.Value); element.SetAttributeNode(attribute); } if (reader.TokenType == JsonToken.String) { element.AppendChild(document.CreateTextNode(reader.Value.ToString())); } else if (reader.TokenType == JsonToken.Integer) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((long)reader.Value))); } else if (reader.TokenType == JsonToken.Float) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((double)reader.Value))); } else if (reader.TokenType == JsonToken.Boolean) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((bool)reader.Value))); } else if (reader.TokenType == JsonToken.Date) { DateTime d = (DateTime)reader.Value; element.AppendChild(document.CreateTextNode(XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind)))); } else if (reader.TokenType == JsonToken.Null) { // empty element. do nothing } else { // finished element will have no children to deserialize if (reader.TokenType != JsonToken.EndObject) { manager.PushScope(); DeserializeNode(reader, document, manager, element); manager.PopScope(); } } }
private void DeserializeValue(Newtonsoft.Json.JsonReader reader, XmlDocument document, XmlNamespaceManager manager, string propertyName, XmlNode currentNode) { // deserialize xml element bool finishedAttributes = false; bool finishedElement = false; Dictionary<string, string> attributeNameValues = new Dictionary<string, string>(); // a string token means the element only has a single text child if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null && reader.TokenType != JsonToken.Boolean && reader.TokenType != JsonToken.Integer && reader.TokenType != JsonToken.Float && reader.TokenType != JsonToken.Date && reader.TokenType != JsonToken.StartConstructor) { // read properties until first non-attribute is encountered while (!finishedAttributes && !finishedElement && reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: string attributeName = reader.Value.ToString(); if (attributeName[0] == '@') { attributeName = attributeName.Substring(1); reader.Read(); string attributeValue = reader.Value.ToString(); attributeNameValues.Add(attributeName, attributeValue); } else { finishedAttributes = true; } break; case JsonToken.EndObject: finishedElement = true; break; default: throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType); } } } // have to wait until attributes have been parsed before creating element // attributes may contain namespace info used by the element XmlElement element = document.CreateElement(propertyName); currentNode.AppendChild(element); // add attributes to newly created element foreach (KeyValuePair<string, string> nameValue in attributeNameValues) { XmlAttribute attribute = document.CreateAttribute(nameValue.Key); attribute.Value = nameValue.Value; element.SetAttributeNode(attribute); } if (reader.TokenType == JsonToken.String) { element.AppendChild(document.CreateTextNode(reader.Value.ToString())); } else if (reader.TokenType == JsonToken.Integer) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((long)reader.Value))); } else if (reader.TokenType == JsonToken.Float) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((double)reader.Value))); } else if (reader.TokenType == JsonToken.Boolean) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((bool)reader.Value))); } else if (reader.TokenType == JsonToken.Date) { DateTime d = (DateTime)reader.Value; element.AppendChild(document.CreateTextNode(XmlConvert.ToString(d, ToSerializationMode(d.Kind)))); } else if (reader.TokenType == JsonToken.Null) { // empty element. do nothing } else { // finished element will have no children to deserialize if (!finishedElement) { manager.PushScope(); DeserializeNode(reader, document, manager, element); manager.PopScope(); } } }
public void ValidateWithXmlReader(XmlSchemaSet schemas, string xml, string xsd) { XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable()); XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.AllowXmlAttributes; XmlSchemaValidator validator = new XmlSchemaValidator(namespaceManager.NameTable, schemas, namespaceManager, validationFlags); validator.Initialize(); using (XmlReader r = XmlReader.Create(xsd)) { while (r.Read()) { switch (r.NodeType) { case XmlNodeType.Element: namespaceManager.PushScope(); if (r.MoveToFirstAttribute()) { do { if (r.NamespaceURI == "http://www.w3.org/2000/xmlns/") { namespaceManager.AddNamespace(r.LocalName, r.Value); } } while (r.MoveToNextAttribute()); r.MoveToElement(); } validator.ValidateElement(r.LocalName, r.NamespaceURI, null, null, null, null, null); if (r.MoveToFirstAttribute()) { do { if (r.NamespaceURI != "http://www.w3.org/2000/xmlns/") { validator.ValidateAttribute(r.LocalName, r.NamespaceURI, r.Value, null); } } while (r.MoveToNextAttribute()); r.MoveToElement(); } validator.ValidateEndOfAttributes(null); if (r.IsEmptyElement) goto case XmlNodeType.EndElement; break; case XmlNodeType.EndElement: validator.ValidateEndElement(null); namespaceManager.PopScope(); break; case XmlNodeType.Text: validator.ValidateText(r.Value); break; case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: validator.ValidateWhitespace(r.Value); break; default: break; } } validator.EndValidation(); } XmlReaderSettings rs = new XmlReaderSettings(); rs.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); rs.ValidationType = ValidationType.Schema; rs.Schemas.XmlResolver = new XmlUrlResolver(); rs.Schemas.Add(null, XmlReader.Create(xsd)); using (XmlReader r = XmlReader.Create(xml, rs)) { while (r.Read()) ; } Assert.Equal(warningCount, 0); Assert.Equal(errorCount, 0); }
private void DeserializeValue(JsonReader reader, XmlDocument document, XmlNamespaceManager manager, string propertyName, XmlNode currentNode) { switch (propertyName) { case TextName: currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString())); break; case CDataName: currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString())); break; case WhitespaceName: currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString())); break; case SignificantWhitespaceName: currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString())); break; default: // processing instructions and the xml declaration start with ? if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?') { if (propertyName == DeclarationName) { string version = null; string encoding = null; string standalone = null; while (reader.Read() && reader.TokenType != JsonToken.EndObject) { switch (reader.Value.ToString()) { case "@version": reader.Read(); version = reader.Value.ToString(); break; case "@encoding": reader.Read(); encoding = reader.Value.ToString(); break; case "@standalone": reader.Read(); standalone = reader.Value.ToString(); break; default: throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value); } } XmlDeclaration declaration = document.CreateXmlDeclaration(version, encoding, standalone); currentNode.AppendChild(declaration); } else { XmlProcessingInstruction instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString()); currentNode.AppendChild(instruction); } } else { // deserialize xml element bool finishedAttributes = false; bool finishedElement = false; string elementPrefix = GetPrefix(propertyName); Dictionary<string, string> attributeNameValues = new Dictionary<string, string>(); // a string token means the element only has a single text child if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null && reader.TokenType != JsonToken.Boolean && reader.TokenType != JsonToken.Integer && reader.TokenType != JsonToken.Float && reader.TokenType != JsonToken.Date && reader.TokenType != JsonToken.StartConstructor) { // read properties until first non-attribute is encountered while (!finishedAttributes && !finishedElement && reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: string attributeName = reader.Value.ToString(); if (attributeName[0] == '@') { attributeName = attributeName.Substring(1); reader.Read(); string attributeValue = reader.Value.ToString(); attributeNameValues.Add(attributeName, attributeValue); string namespacePrefix; if (IsNamespaceAttribute(attributeName, out namespacePrefix)) { manager.AddNamespace(namespacePrefix, attributeValue); } } else { finishedAttributes = true; } break; case JsonToken.EndObject: finishedElement = true; break; default: throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType); } } } // have to wait until attributes have been parsed before creating element // attributes may contain namespace info used by the element XmlElement element = (!string.IsNullOrEmpty(elementPrefix)) ? document.CreateElement(propertyName, manager.LookupNamespace(elementPrefix)) : document.CreateElement(propertyName); currentNode.AppendChild(element); // add attributes to newly created element foreach (KeyValuePair<string, string> nameValue in attributeNameValues) { string attributePrefix = GetPrefix(nameValue.Key); XmlAttribute attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix)) : document.CreateAttribute(nameValue.Key); attribute.Value = nameValue.Value; element.SetAttributeNode(attribute); } if (reader.TokenType == JsonToken.String) { element.AppendChild(document.CreateTextNode(reader.Value.ToString())); } else if (reader.TokenType == JsonToken.Integer) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((long)reader.Value))); } else if (reader.TokenType == JsonToken.Float) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((double)reader.Value))); } else if (reader.TokenType == JsonToken.Boolean) { element.AppendChild(document.CreateTextNode(XmlConvert.ToString((bool)reader.Value))); } else if (reader.TokenType == JsonToken.Date) { DateTime d = (DateTime)reader.Value; element.AppendChild(document.CreateTextNode(XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind)))); } else if (reader.TokenType == JsonToken.Null) { // empty element. do nothing } else { // finished element will have no children to deserialize if (!finishedElement) { manager.PushScope(); DeserializeNode(reader, document, manager, element); manager.PopScope(); } } } break; } }
private void CreateElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string elementName, XmlNamespaceManager manager, string elementPrefix, Dictionary<string, string> attributeNameValues) { IXmlElement element = CreateElement(elementName, document, elementPrefix, manager); currentNode.AppendChild(element); // add attributes to newly created element foreach (KeyValuePair<string, string> nameValue in attributeNameValues) { string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value) : document.CreateAttribute(nameValue.Key, nameValue.Value); element.SetAttributeNode(attribute); } if (reader.TokenType == JsonToken.String || reader.TokenType == JsonToken.Integer || reader.TokenType == JsonToken.Float || reader.TokenType == JsonToken.Boolean || reader.TokenType == JsonToken.Date) { element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader))); } else if (reader.TokenType == JsonToken.Null) { // empty element. do nothing } else { // finished element will have no children to deserialize if (reader.TokenType != JsonToken.EndObject) { manager.PushScope(); DeserializeNode(reader, document, manager, element); manager.PopScope(); } manager.RemoveNamespace(string.Empty, manager.DefaultNamespace); } }
private void RemoveDuplicateNamespace(XmlElement elem, XmlNamespaceManager mgr, bool fCheckElemAttrs) { //remove the duplicate attributes on current node first mgr.PushScope(); XmlAttributeCollection attrs = elem.Attributes; int cAttrs = attrs.Count; if (fCheckElemAttrs && cAttrs > 0) { for (int i = cAttrs - 1; i >= 0; --i) { XmlAttribute attr = attrs[i]; if (attr.Prefix == _doc.strXmlns) { string nsUri = mgr.LookupNamespace(attr.LocalName); if (nsUri != null) { if (attr.Value == nsUri) { elem.Attributes.RemoveNodeAt(i); } } else { // Add this namespace, so it we will behave correctly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as // InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>" // If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for // the subsequent InnerXml_set or setting an EntRef inside. mgr.AddNamespace(attr.LocalName, attr.Value); } } else if (attr.Prefix.Length == 0 && attr.LocalName == _doc.strXmlns) { string nsUri = mgr.DefaultNamespace; if (nsUri != null) { if (attr.Value == nsUri) { elem.Attributes.RemoveNodeAt(i); } } else { // Add this namespace, so it we will behave correctly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as // InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>" // If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for // the subsequent InnerXml_set or setting an EntRef inside. mgr.AddNamespace(attr.LocalName, attr.Value); } } } } //now recursively remove the duplicate attributes on the children XmlNode child = elem.FirstChild; while (child != null) { XmlElement childElem = child as XmlElement; if (childElem != null) { RemoveDuplicateNamespace(childElem, mgr, true); } child = child.NextSibling; } mgr.PopScope(); }
private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) { if (string.IsNullOrEmpty(propertyName)) throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML."); var attributeNameValues = ReadAttributeElements(reader, manager); var elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); if (propertyName.StartsWith('@')) { var attributeName = propertyName.Substring(1); var attributeValue = reader.Value.ToString(); var attributePrefix = MiscellaneousUtils.GetPrefix(attributeName); var attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(attributeName, manager.LookupNamespace(attributePrefix), attributeValue) : document.CreateAttribute(attributeName, attributeValue); ((IXmlElement) currentNode).SetAttributeNode(attribute); } else { var element = CreateElement(propertyName, document, elementPrefix, manager); currentNode.AppendChild(element); // add attributes to newly created element foreach (var nameValue in attributeNameValues) { var attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); var attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value) : document.CreateAttribute(nameValue.Key, nameValue.Value); element.SetAttributeNode(attribute); } switch (reader.TokenType) { case JsonToken.Date: case JsonToken.Boolean: case JsonToken.Float: case JsonToken.Integer: case JsonToken.String: element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader))); break; case JsonToken.Null: break; default: if (reader.TokenType != JsonToken.EndObject) { manager.PushScope(); DeserializeNode(reader, document, manager, element); manager.PopScope(); } manager.RemoveNamespace(string.Empty, manager.DefaultNamespace); break; } } }