private static XmlNamespaceManager GetNsMgr(string csprojFile) { XmlNamespaceManager nsmgr = new XmlNamespaceManager(new XmlTextReader(csprojFile).NameTable); nsmgr.AddNamespace(Constants.MSBUILD, "http://schemas.microsoft.com/developer/msbuild/2003"); nsmgr.PushScope(); return nsmgr; }
private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager) { List<IXmlNode> list = (List<IXmlNode>) null; IXmlNode xmlNode1 = node; while ((xmlNode1 = xmlNode1.ParentNode) != null) { if (xmlNode1.NodeType == XmlNodeType.Element) { if (list == null) list = new List<IXmlNode>(); list.Add(xmlNode1); } } if (list == null) return; list.Reverse(); foreach (IXmlNode xmlNode2 in list) { manager.PushScope(); foreach (IXmlNode xmlNode3 in (IEnumerable<IXmlNode>) xmlNode2.Attributes) { if (xmlNode3.NamespaceUri == "http://www.w3.org/2000/xmlns/" && xmlNode3.LocalName != "xmlns") manager.AddNamespace(xmlNode3.LocalName, xmlNode3.Value); } } }
// // Private methods // private void ProcessNamespaces() { switch (reader.NodeType) { case XmlNodeType.Element: nsManager.PushScope(); string prefix = reader.Prefix; string ns = reader.NamespaceURI; if (nsManager.LookupNamespace(prefix) != ns) { AddNamespace(prefix, ns); } if (reader.MoveToFirstAttribute()) { do { prefix = reader.Prefix; ns = reader.NamespaceURI; if (Ref.Equal(ns, xmlnsUri)) { if (prefix.Length == 0) { nsManager.AddNamespace(string.Empty, reader.Value); RemoveNamespace(string.Empty, xmlns); } else { prefix = reader.LocalName; nsManager.AddNamespace(prefix, reader.Value); RemoveNamespace(xmlns, prefix); } } else if (prefix.Length != 0 && nsManager.LookupNamespace(prefix) != ns) { AddNamespace(prefix, ns); } } while (reader.MoveToNextAttribute()); reader.MoveToElement(); } if (reader.IsEmptyElement) { state = State.PopNamespaceScope; } break; case XmlNodeType.EndElement: state = State.PopNamespaceScope; break; } }
public VSProject CreateVSProjectFromFromFolder(string name, string folder, ProjectType type) { XmlDocument doc = new XmlDocument(new NameTable()); XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable); nsManager.AddNamespace("", "http://schemas.microsoft.com/developer/msbuild/2003"); nsManager.PushScope(); doc.Load(Path.Combine(context.TemplateFolder.FullName, "VS/CSProject_template.xml")); return VSProject.Create(name, folder, type, doc); }
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); } } }
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(); }
private XmlParserContext GetContext(XmlNode node) { string xmlLang = null; XmlSpace none = XmlSpace.None; XmlDocumentType documentType = this.doc.DocumentType; string baseURI = this.doc.BaseURI; Hashtable hashtable = new Hashtable(); XmlNameTable nameTable = this.doc.NameTable; XmlNamespaceManager nsMgr = new XmlNamespaceManager(nameTable); bool flag = false; while ((node != null) && (node != this.doc)) { if ((node is XmlElement) && ((XmlElement)node).HasAttributes) { nsMgr.PushScope(); foreach (XmlAttribute attribute in ((XmlElement)node).Attributes) { if ((attribute.Prefix == this.doc.strXmlns) && !hashtable.Contains(attribute.LocalName)) { hashtable.Add(attribute.LocalName, attribute.LocalName); nsMgr.AddNamespace(attribute.LocalName, attribute.Value); } else if ((!flag && (attribute.Prefix.Length == 0)) && (attribute.LocalName == this.doc.strXmlns)) { nsMgr.AddNamespace(string.Empty, attribute.Value); flag = true; } else if (((none == XmlSpace.None) && (attribute.Prefix == this.doc.strXml)) && (attribute.LocalName == this.doc.strSpace)) { if (attribute.Value == "default") { none = XmlSpace.Default; } else if (attribute.Value == "preserve") { none = XmlSpace.Preserve; } } else if (((xmlLang == null) && (attribute.Prefix == this.doc.strXml)) && (attribute.LocalName == this.doc.strLang)) { xmlLang = attribute.Value; } } } node = node.ParentNode; } return(new XmlParserContext(nameTable, nsMgr, (documentType == null) ? null : documentType.Name, (documentType == null) ? null : documentType.PublicId, (documentType == null) ? null : documentType.SystemId, (documentType == null) ? null : documentType.InternalSubset, baseURI, xmlLang, none)); }
internal XQueryContextManager (XQueryStaticContext ctx, XPathItem input, XmlWriter writer, XmlResolver resolver, XmlArgumentList args) { this.input = input; this.staticContext = ctx; this.args = args; currentWriter = writer; this.extDocResolver = resolver; namespaceManager = new XmlNamespaceManager (ctx.NameTable); foreach (DictionaryEntry de in ctx.NSResolver.GetNamespacesInScope (XmlNamespaceScope.ExcludeXml)) namespaceManager.AddNamespace (de.Key.ToString (), de.Value.ToString ()); namespaceManager.PushScope (); currentContext = new XQueryContext (this, null, new Hashtable ()); if (input != null) { currentSequence = new SingleItemIterator (input, currentContext); currentSequence.MoveNext (); } currentContext = new XQueryContext (this, currentSequence, new Hashtable ()); }
/// <summary> /// Get YouTube thumbnail of the video with specified ID /// </summary> /// <param name="id">Id of the video to get thumbnail of</param> /// <returns>BitmapSource of the preview</returns> internal static BitmapSource GetThumbBitmapFromYT(string id) { XmlDocument doc = new XmlDocument(); XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable); doc.Load("http://gdata.youtube.com/feeds/api/videos/" + id); ns.AddNamespace("", "http://www.w3.org/2005/Atom"); ns.AddNamespace("media", "http://search.yahoo.com/mrss/"); ns.PushScope(); XmlElement root = doc.DocumentElement; XmlNodeList list = root.ChildNodes; string videoThumbUrl; foreach (XmlNode node in list) { if (node.Name == "media:group") { XmlNode thumbnail = node.SelectSingleNode("media:thumbnail", ns); videoThumbUrl = thumbnail.Attributes["url"].Value; return Utils.GetImage(new Uri(videoThumbUrl)); } } return null; }
private static XmlNamespaceManager GetNamespaceManager(XmlNode node, XmlDocument document) { XmlNamespaceManager namespaceManager = new XmlNamespaceManager(document.NameTable); List<XmlElement> elements = new List<XmlElement>(); while (node != null) { XmlElement element = node as XmlElement; if (element != null && element.HasAttributes) { elements.Add(element); } node = node.ParentNode; } for (int i = elements.Count - 1; i >= 0; i--) { namespaceManager.PushScope(); XmlAttributeCollection attributes = elements[i].Attributes; for (int j = 0; j < attributes.Count; j++) { XmlAttribute attribute = attributes[j]; if (attribute.IsNamespace()) { string prefix = attribute.Prefix.Length == 0 ? string.Empty : attribute.LocalName; namespaceManager.AddNamespace(prefix, attribute.Value); } } } return namespaceManager; }
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 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); }
// 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 override XmlDocument ProcessContent(XmlDocument docToProcess) { Message (TraceLevel.Info, "x1"); XmlNamespaceManager nsmgr = new XmlNamespaceManager(docToProcess.NameTable); nsmgr.AddNamespace("default", "http://www.w3.org/1999/xhtml"); nsmgr.AddNamespace("monodoc", "http://www.go-mono.org/xml/monodoc"); nsmgr.PushScope(); Message (TraceLevel.Info, "x2"); XmlElement root = docToProcess.DocumentElement; XmlNode body = root.SelectSingleNode("/default:html/default:body", nsmgr); // Use the DC.Description meta tag as sign, that the file is in the new format Message (TraceLevel.Info, "x3"); if (root.SelectNodes("/default:html/default:head/default:meta[@name='DC.Description']", nsmgr).Count != 0) { ////////////////////////////////////////////////////////////////////// // Start of temporary code, until the tutorial is converted completely ////////////////////////////////////////////////////////////////////// XmlNodeList nodeList = docToProcess.GetElementsByTagName("div"); /* Remove the mono handbook specific decorations */ foreach(XmlNode node in nodeList) { string cssClass = ((XmlElement)node).GetAttribute("class"); if (cssClass != null && (cssClass == "topframe" || cssClass == "navbar" || cssClass == "copyright")) { node.RemoveAll(); } } string headinginner = "Mono Handbook"; XmlNode firstheading = docToProcess.GetElementsByTagName("title")[0]; headinginner = firstheading.InnerXml; try { XmlNode bodynode = docToProcess.GetElementsByTagName("body")[0]; bodynode.InnerXml = "<table width=\"100%\">" + "<tr bgcolor=\"#b0c4de\"><td><i></i>Mono Handbook<h3>" + headinginner + "</h3></td></tr></table><p />" + bodynode.InnerXml; } catch { } Message (TraceLevel.Info, "x5"); ////////////////////////////////////////////////////////////////////// // End of temporary code, until the tutorial is converted completely ////////////////////////////////////////////////////////////////////// XmlNodeList nodeList2 = docToProcess.GetElementsByTagName("pre"); foreach(XmlNode node in nodeList2) { string cssClass = ((XmlElement)node).GetAttribute("class"); if (cssClass != null) { switch(cssClass) { case "code": node.InnerXml = "<table width='100%' border='0' cellspacing='0' cellpadding='3'><tr><td>" + "<table width='100%' border='0' cellspacing='0' cellpadding='0' height='100%'>" + "<tr><td bgcolor='#c0c0c0'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#c0c0c0'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#c0c0c0'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "</tr><tr> <td bgcolor='#c0c0c0'> </td><td width='100%' bgcolor='#efefef'> " + "<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td bgcolor='#ffffff'>" + "<table width='100%' border='0' cellspacing='0' cellpadding='2'><tr><td bgcolor='#efefef'><pre>" + node.InnerXml + "</pre></td></tr></table></td></tr></table></td><td bgcolor='#999999'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "</tr><tr> <td bgcolor='#c0c0c0'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#c0c0c0'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#c0c0c0'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "</tr></table></td></tr></table>"; break; case "console": node.InnerXml = "<table width='100%' border='0' cellspacing='0' cellpadding='3'><tr><td>" + "<table width='100%' border='0' cellspacing='0' cellpadding='0' height='100%'>" + "<tr><td bgcolor='#555555'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#555555'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#555555'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "</tr><tr> <td bgcolor='#c0c0c0'> </td><td width='100%' bgcolor='#efefef'> " + "<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td bgcolor='#ffffff'>" + "<table width='100%' border='0' cellspacing='0' cellpadding='2'><tr><td bgcolor='#999999'><pre>" + node.InnerXml + "</pre></td></tr></table></td></tr></table></td><td bgcolor='#999999'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "</tr><tr> <td bgcolor='#555555'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#555555'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#555555'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "</tr></table></td></tr></table>"; break; default: break; } } } nodeList = root.SelectNodes("//monodoc:example", nsmgr); foreach (XmlNode node in nodeList) { //XmlNode csnode = root.SelectSingleNode("/monodoc:source[@lang='CS']", nsmgr); body.RemoveChild(node); } //string copyright_string = ""; // no string for now nodeList = root.SelectNodes("//default:link[@type='text/css']", nsmgr); if (nodeList.Count == 0) { // TODO: Stylesheet path maybe variable root.SelectSingleNode("/default:html/default:head", nsmgr).InnerXml += "\n <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />"; } string contributor_string = "<a id=\"credits\"><h2>Credits</h2></a>"; nodeList = root.SelectNodes("//default:meta[@name='DC.Contributor']", nsmgr); foreach (XmlNode node in nodeList) { contributor_string += node.Attributes.GetNamedItem("content").Value + "<br />\n"; } // body.InnerXml += contributor_string + copyright_string; } else { Message (TraceLevel.Info, "x4"); XmlNodeList nodeList = docToProcess.GetElementsByTagName("div"); if (nodeList != null){ /* Remove the mono handbook specific decorations */ foreach(XmlNode node in nodeList) { string cssClass = ((XmlElement)node).GetAttribute("class"); if (cssClass != null && (cssClass == "topframe" || cssClass == "navbar" || cssClass == "copyright")){ node.RemoveAll(); } } } Message (TraceLevel.Info, "x6"); string headinginner = "Mono Handbook"; XmlNode firstheading = null; try { firstheading = docToProcess.GetElementsByTagName("h1")[0]; headinginner = firstheading.InnerXml; } catch { try { firstheading = docToProcess.GetElementsByTagName("h2")[0]; headinginner = firstheading.InnerXml; } catch {} } Message (TraceLevel.Info, "x8"); try { XmlNode bodynode = docToProcess.GetElementsByTagName("body")[0]; if (firstheading != null) bodynode.RemoveChild(firstheading); bodynode.InnerXml = "<table width=\"100%\">" + "<tr bgcolor=\"#b0c4de\"><td><i></i>Mono Handbook<h3>" + headinginner + "</h3></td></tr></table><p />" + bodynode.InnerXml; } catch { } Message (TraceLevel.Info, "x9"); XmlNodeList nodeList2 = docToProcess.GetElementsByTagName("pre"); foreach(XmlNode node in nodeList2){ string cssClass = ((XmlElement)node).GetAttribute("class"); if (cssClass != null){ switch(cssClass) { case "code": node.InnerXml = "<table width='100%' border='0' cellspacing='0' cellpadding='3'><tr><td>" + "<table width='100%' border='0' cellspacing='0' cellpadding='0' height='100%'>" + "<tr><td bgcolor='#c0c0c0'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#c0c0c0'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#c0c0c0'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "</tr><tr> <td bgcolor='#c0c0c0'> </td><td width='100%' bgcolor='#efefef'> " + "<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td bgcolor='#ffffff'>" + "<table width='100%' border='0' cellspacing='0' cellpadding='2'><tr><td bgcolor='#efefef'>" + "<pre>" + node.InnerXml + "</pre>" + "</td></tr></table></td></tr></table></td><td bgcolor='#999999'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "</tr><tr> <td bgcolor='#c0c0c0'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#c0c0c0'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#c0c0c0'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "</tr></table></td></tr></table>"; break; case "console": node.InnerXml = "<table width='100%' border='0' cellspacing='0' cellpadding='3'><tr><td>" + "<table width='100%' border='0' cellspacing='0' cellpadding='0' height='100%'>" + "<tr><td bgcolor='#555555'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#555555'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#555555'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "</tr><tr> <td bgcolor='#c0c0c0'> </td><td width='100%' bgcolor='#efefef'> " + "<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td bgcolor='#ffffff'>" + "<table width='100%' border='0' cellspacing='0' cellpadding='2'><tr><td bgcolor='#999999'>" + "<pre>" + node.InnerXml + "</pre>" + "</td></tr></table></td></tr></table></td><td bgcolor='#999999'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "</tr><tr> <td bgcolor='#555555'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#555555'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "<td bgcolor='#555555'><img src='/html/en/images/empty.png' width='1' height='1' /></td>" + "</tr></table></td></tr></table>"; break; default: break; } } } } return docToProcess; }
#pragma warning restore 618 private XmlParserContext GetContext(XmlNode node) { String lang = null; XmlSpace spaceMode = XmlSpace.None; XmlDocumentType docType = _doc.DocumentType; String baseURI = _doc.BaseURI; //constructing xmlnamespace HashSet<string> prefixes = new HashSet<string>(); XmlNameTable nt = _doc.NameTable; XmlNamespaceManager mgr = new XmlNamespaceManager(nt); bool bHasDefXmlnsAttr = false; // Process all xmlns, xmlns:prefix, xml:space and xml:lang attributes while (node != null && node != _doc) { XmlElement element = node as XmlElement; if (element != null && element.HasAttributes) { mgr.PushScope(); foreach (XmlAttribute attr in element.Attributes) { if (attr.Prefix == _doc.strXmlns && !prefixes.Contains(attr.LocalName)) { // Make sure the next time we will not add this prefix prefixes.Add(attr.LocalName); mgr.AddNamespace(attr.LocalName, attr.Value); } else if (!bHasDefXmlnsAttr && attr.Prefix.Length == 0 && attr.LocalName == _doc.strXmlns) { // Save the case xmlns="..." where xmlns is the LocalName mgr.AddNamespace(String.Empty, attr.Value); bHasDefXmlnsAttr = true; } else if (spaceMode == XmlSpace.None && attr.Prefix == _doc.strXml && attr.LocalName == _doc.strSpace) { // Save xml:space context if (attr.Value == "default") spaceMode = XmlSpace.Default; else if (attr.Value == "preserve") spaceMode = XmlSpace.Preserve; } else if (lang == null && attr.Prefix == _doc.strXml && attr.LocalName == _doc.strLang) { // Save xml:lag context lang = attr.Value; } } } node = node.ParentNode; } return new XmlParserContext( nt, mgr, (docType == null) ? null : docType.Name, (docType == null) ? null : docType.PublicId, (docType == null) ? null : docType.SystemId, (docType == null) ? null : docType.InternalSubset, baseURI, lang, spaceMode ); }
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 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(); } } }
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"); }
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)); }
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")); }
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); }
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); } }
XmlDocument ShowComments(XmlDocument docToProcess, string code) { XmlNamespaceManager nsmgr = new XmlNamespaceManager(docToProcess.NameTable); nsmgr.AddNamespace("default", "http://www.w3.org/1999/xhtml"); nsmgr.AddNamespace("monodoc", "http://www.go-mono.org/xml/monodoc"); nsmgr.PushScope(); XmlElement root = docToProcess.DocumentElement; XmlNode body = root.SelectSingleNode("/default:html/default:body", nsmgr); string html = "<br /><hr /><br />"; CommentService commentservice = new CommentService(); Comment[] comments = commentservice.GetCommentsByUrl("monohb@" + code); if (comments == null) { html += "No comments available."; } else { foreach(Comment comment in comments) { if (comment.Title == "") comment.Title = "[No Title]"; html += "<table width=\"100%\" cellpadding=\"4\" cellspacing=\"2\" bgcolor=\"#efefef\">\n"; html += "<tr><td valign=\"top\" bgcolor=\"#c0c0c0\" class=\"commenthead\" colspan=\"2\"><b>" + comment.Title + "</b> </td></tr>\n"; html += "<tr><td width=\"100\" valign=\"top\" class=\"commentcontent\"><b>Author:</b>" + "</td><td valign=\"top\" class=\"commentcontent\">" + comment.Author + "</td></tr>\n"; html += "<tr><td width=\"100\" valign=\"top\" class=\"commentcontent\"><b>Mail:</b>" + "</td><td valign=\"top\" class=\"commentcontent\">" + comment.Mail + "</td></tr>\n"; html += "<tr><td width=\"100\" valign=\"top\" class=\"commentcontent\"><b>Date:</b>" + "</td><td valign=\"top\" class=\"commentcontent\">" + comment.Date + "</td></tr>\n"; html += "<tr><td width=\"100\" valign=\"top\" class=\"commentcontent\"><b>Comment:</b>" + "</td><td valign=\"top\" class=\"commentcontent\">" + comment.Text + "</td></tr>\n"; html += "</table>\n\n<br /><br />\n" ; } } Console.WriteLine("monohb@" + code); body.InnerXml += html; return docToProcess; }
public static XmlNamespaceManager GatherOuterNamespaces( ElementItem element, NameTable nt) { XmlNamespaceManager nsColl = new XmlNamespaceManager(nt); ElementItem current = element; string strName = element.Name; while(true) { if (current == null || current == current.m_document.VirtualRoot) { break; } nsColl.PushScope(); foreach(AttrItem attr in current.attrs) { if (attr.IsNamespace == false) continue; nsColl.AddNamespace(attr.LocalName, attr.GetValue()); // 只要prefix重就不加入 } current = (ElementItem)current.parent; } return nsColl; }
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 static XmlNamespaceManager GetNamespaceManager(XmlNode node, XmlDocument document) { XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable); List<XmlElement> list = new List<XmlElement>(); while (node != null) { XmlElement item = node as XmlElement; if ((item != null) && item.HasAttributes) { list.Add(item); } node = node.ParentNode; } for (int i = list.Count - 1; i >= 0; i--) { manager.PushScope(); XmlAttributeCollection attributes = list[i].Attributes; for (int j = 0; j < attributes.Count; j++) { XmlAttribute attribute = attributes[j]; if (attribute.IsNamespace) { string prefix = (attribute.Prefix.Length == 0) ? string.Empty : attribute.LocalName; manager.AddNamespace(prefix, attribute.Value); } } } return manager; }
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); } }
public SvgDocument() { this.styleElements = new ArrayList(); this.recordanim = true; this.playAnim = false; this.controltime = 0; this.filename = "���"; this.update = true; this.undoStack = new UndoStack(); this.xmlreader = null; this.preelement = null; this.elements = new ArrayList(0x10); this.infos = new Hashtable(0x10); this.groups = new ArrayList(0x10); this.undoGroup = new ArrayList(0x10); this.errorinfos = new ArrayList(0x10); this.selectCollection = new SvgElementCollection(); this.oldSelect = new SvgElementCollection(); this.root = null; this.serialize = null; this.editRoots = new SvgElementCollection(); //this.styleSheetList = null; this.ChangeElements = new SvgElementCollection(); this.NumberOfUndoOperations = 1; this.ValidPath = new GraphicsPath(); this.firstload = false; this.FilePath = string.Empty; this.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; this.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault; this.Changed = false; this.SelectChanged = false; this.OnlyShowCurrent = false; this.DefsChanged = true; this.OldControlTime = 0; this.PlayAnimChanged = false; this.AutoShowAnim = false; this.XmlParserContext = null; XmlNamespaceManager manager1 = new XmlNamespaceManager(base.NameTable); manager1.PushScope(); manager1.AddNamespace("svg", SvgDocument.SvgNamespace); manager1.AddNamespace("xlink", SvgDocument.XLinkNamespace); manager1.AddNamespace("a", SvgDocument.AudioNamespace); manager1.AddNamespace("tonli", SvgDocument.TonliNamespace); base.NodeChanged += new XmlNodeChangedEventHandler(this.ChangeNode); base.NodeInserted += new XmlNodeChangedEventHandler(this.ChangeNode); base.NodeRemoved += new XmlNodeChangedEventHandler(this.ChangeNode); this.XmlParserContext = new System.Xml.XmlParserContext(base.NameTable, manager1, "", "svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", this.BaseURI, "zh", XmlSpace.None, Encoding.UTF8); this.selectCollection.NotifyEvent = true; this.selectCollection.OnCollectionChangedEvent += new OnCollectionChangedEventHandler(this.ChangeSelect); this.serialize = new SerializeDocument(this); this.AddStyleElement(SvgDocument.SvgNamespace, "style"); this.SvgdataUid=string.Empty; layers =new SvgElementCollection(); }
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(); } } }
// 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 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 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 PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager) { List<IXmlNode> parentElements = null; IXmlNode parent = node; while ((parent = parent.ParentNode) != null) { if (parent.NodeType == XmlNodeType.Element) { if (parentElements == null) parentElements = new List<IXmlNode>(); parentElements.Add(parent); } } if (parentElements != null) { parentElements.Reverse(); foreach (IXmlNode parentElement in parentElements) { manager.PushScope(); foreach (IXmlNode attribute in parentElement.Attributes) { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns") manager.AddNamespace(attribute.LocalName, attribute.Value); } } } }
// Token: 0x060006DC RID: 1756 // RVA: 0x00037820 File Offset: 0x00035A20 private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager) { List<IXmlNode> list = null; IXmlNode xmlNode = node; while ((xmlNode = xmlNode.ParentNode) != null) { if (xmlNode.NodeType == XmlNodeType.Element) { if (list == null) { list = new List<IXmlNode>(); } list.Add(xmlNode); } } if (list != null) { list.Reverse(); foreach (IXmlNode current in list) { manager.PushScope(); foreach (IXmlNode current2 in current.Attributes) { if (current2.NamespaceUri == "http://www.w3.org/2000/xmlns/" && current2.LocalName != "xmlns") { manager.AddNamespace(current2.LocalName, current2.Value); } } } } }
#pragma warning restore 618 private XmlParserContext GetContext(XmlNode node) { String lang = null; XmlSpace spaceMode = XmlSpace.None; XmlDocumentType docType = _doc.DocumentType; String baseURI = _doc.BaseURI; //constructing xmlnamespace HashSet <string> prefixes = new HashSet <string>(); XmlNameTable nt = _doc.NameTable; XmlNamespaceManager mgr = new XmlNamespaceManager(nt); bool bHasDefXmlnsAttr = false; // Process all xmlns, xmlns:prefix, xml:space and xml:lang attributes while (node != null && node != _doc) { XmlElement element = node as XmlElement; if (element != null && element.HasAttributes) { mgr.PushScope(); foreach (XmlAttribute attr in element.Attributes) { if (attr.Prefix == _doc.strXmlns && !prefixes.Contains(attr.LocalName)) { // Make sure the next time we will not add this prefix prefixes.Add(attr.LocalName); mgr.AddNamespace(attr.LocalName, attr.Value); } else if (!bHasDefXmlnsAttr && attr.Prefix.Length == 0 && attr.LocalName == _doc.strXmlns) { // Save the case xmlns="..." where xmlns is the LocalName mgr.AddNamespace(String.Empty, attr.Value); bHasDefXmlnsAttr = true; } else if (spaceMode == XmlSpace.None && attr.Prefix == _doc.strXml && attr.LocalName == _doc.strSpace) { // Save xml:space context if (attr.Value == "default") { spaceMode = XmlSpace.Default; } else if (attr.Value == "preserve") { spaceMode = XmlSpace.Preserve; } } else if (lang == null && attr.Prefix == _doc.strXml && attr.LocalName == _doc.strLang) { // Save xml:lag context lang = attr.Value; } } } node = node.ParentNode; } return(new XmlParserContext( nt, mgr, (docType == null) ? null : docType.Name, (docType == null) ? null : docType.PublicId, (docType == null) ? null : docType.SystemId, (docType == null) ? null : docType.InternalSubset, baseURI, lang, spaceMode )); }
// 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); }