// Test the default namespace manager properties. public void TestXmlNamespaceManagerDefaults() { NameTable table = new NameTable(); XmlNamespaceManager ns = new XmlNamespaceManager(table); AssertEquals("Defaults (1)", "http://www.w3.org/XML/1998/namespace", ns.LookupNamespace("xml")); AssertEquals("Defaults (2)", "http://www.w3.org/2000/xmlns/", ns.LookupNamespace("xmlns")); AssertEquals("Defaults (3)", "", ns.LookupNamespace("")); Assert("Defaults (4)", ReferenceEquals(table, ns.NameTable)); AssertEquals("Defaults (5)", "", ns.DefaultNamespace); AssertNull("Defaults (6)", ns.LookupNamespace("foo")); }
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); 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(); } } }
internal static void CreateAndSerialize() { XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable()); const string NamespacePrefix = "dixin"; namespaceManager.AddNamespace(NamespacePrefix, "https://weblogs.asp.net/dixin"); XmlDocument document = new XmlDocument(namespaceManager.NameTable); XmlElement rss = document.CreateElement("rss"); rss.SetAttribute("vewrsion", "2.0"); XmlAttribute attribute = document.CreateAttribute( "xmlns", NamespacePrefix, namespaceManager.LookupNamespace("xmlns")); attribute.Value = namespaceManager.LookupNamespace(NamespacePrefix); rss.SetAttributeNode(attribute); document.AppendChild(rss); XmlElement channel = document.CreateElement("channel"); rss.AppendChild(channel); XmlElement item = document.CreateElement("item"); channel.AppendChild(item); XmlElement title = document.CreateElement("title"); title.InnerText = "LINQ via C#"; item.AppendChild(title); XmlElement link = document.CreateElement("link"); link.InnerText = "https://weblogs.asp.net/dixin/linq-via-csharp"; item.AppendChild(link); XmlElement description = document.CreateElement("description"); description.InnerXml = "<p>This is a tutorial of LINQ and functional programming. Hope it helps.</p>"; item.AppendChild(description); XmlElement pubDate = document.CreateElement("pubDate"); pubDate.InnerText = new DateTime(2009, 9, 7).ToString("r"); item.AppendChild(pubDate); XmlElement guid = document.CreateElement("guid"); guid.InnerText = "https://weblogs.asp.net/dixin/linq-via-csharp"; guid.SetAttribute("isPermaLink", "true"); item.AppendChild(guid); XmlElement category1 = document.CreateElement("category"); category1.InnerText = "C#"; item.AppendChild(category1); XmlNode category2 = category1.CloneNode(false); category2.InnerText = "LINQ"; item.AppendChild(category2); XmlComment comment = document.CreateComment("Comment."); item.AppendChild(comment); XmlElement source = document.CreateElement(NamespacePrefix, "source", namespaceManager.LookupNamespace(NamespacePrefix)); source.InnerText = "https://github.com/Dixin/CodeSnippets/tree/master/Dixin/Linq"; item.AppendChild(source); // Serialize XmlDocument to string. StringBuilder xmlString = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = " ", OmitXmlDeclaration = true }; using (XmlWriter writer = XmlWriter.Create(xmlString, settings)) { document.Save(writer); } // rssItem.ToString() returns "System.Xml.XmlElement". // rssItem.OuterXml returns a single line of XML text. xmlString.WriteLine(); }
private static void StartTag() { var ht = new Hashtable(); if (_reader.HasAttributes) { while (_reader.MoveToNextAttribute()) { if (_reader.Prefix.Equals("xmlns")) { NamespaceManager.AddNamespace(_reader.LocalName, _reader.Value); } else if (_reader.Name.Equals("xmlns")) { NamespaceManager.AddNamespace(string.Empty, _reader.Value); } else { ht.Add(_reader.Name, _reader.Value); } } _reader.MoveToElement(); } var ns = NamespaceManager.LookupNamespace(_reader.Prefix); var q = new XmlQualifiedName(_reader.LocalName, ns); XmlElement elem = TagRegistry.GetTag <Tag>(q); foreach (string attrname in ht.Keys) { var colon = attrname.IndexOf(':'); if (colon > 0) { var prefix = attrname.Substring(0, colon); var name = attrname.Substring(colon + 1); var attr = Tag.Document.CreateAttribute(prefix, name, NamespaceManager.LookupNamespace(prefix)); attr.InnerXml = (string)ht[attrname]; elem.SetAttributeNode(attr); } else { var attr = Tag.Document.CreateAttribute(attrname); attr.InnerXml = (string)ht[attrname]; elem.SetAttributeNode(attr); } } if (_root == null) { if (elem.Name != "stream:stream") { ProtocolState.Events.Error(null, ErrorType.WrongProtocolVersion, ErrorSeverity.Fatal, "Missing proper stream:stream header from server."); return; } _root = elem; } else { _element?.AppendChild(elem); _element = elem; } }
private Dictionary <string, string> ReadAttributeElements( JsonReader reader, XmlNamespaceManager manager) { Dictionary <string, string> dictionary = new Dictionary <string, string>(); bool flag1 = false; bool flag2 = false; 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)) { while (!flag1 && !flag2 && reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: string str1 = reader.Value.ToString(); if (!string.IsNullOrEmpty(str1)) { switch (str1[0]) { case '$': if (str1 == "$values" || str1 == "$id" || (str1 == "$ref" || str1 == "$type") || str1 == "$value") { string prefix = manager.LookupPrefix("http://james.newtonking.com/projects/json"); if (prefix == null) { int?nullable = new int?(); while (manager.LookupNamespace("json" + (object)nullable) != null) { nullable = new int?(nullable.GetValueOrDefault() + 1); } prefix = "json" + (object)nullable; dictionary.Add("xmlns:" + prefix, "http://james.newtonking.com/projects/json"); manager.AddNamespace(prefix, "http://james.newtonking.com/projects/json"); } if (str1 == "$values") { flag1 = true; continue; } string str2 = str1.Substring(1); reader.Read(); if (!JsonTokenUtils.IsPrimitiveToken(reader.TokenType)) { throw JsonSerializationException.Create(reader, "Unexpected JsonToken: " + (object)reader.TokenType); } string str3 = reader.Value != null?reader.Value.ToString() : (string)null; dictionary.Add(prefix + ":" + str2, str3); continue; } flag1 = true; continue; case '@': string str4 = str1.Substring(1); reader.Read(); string xmlValue = this.ConvertTokenToXmlValue(reader); dictionary.Add(str4, xmlValue); string prefix1; if (this.IsNamespaceAttribute(str4, out prefix1)) { manager.AddNamespace(prefix1, xmlValue); continue; } continue; default: flag1 = true; continue; } } else { flag1 = true; continue; } case JsonToken.Comment: flag2 = true; continue; case JsonToken.EndObject: flag2 = true; continue; default: throw JsonSerializationException.Create(reader, "Unexpected JsonToken: " + (object)reader.TokenType); } } } return(dictionary); }
private void CreateElement( JsonReader reader, IXmlDocument document, IXmlNode currentNode, string elementName, XmlNamespaceManager manager, string elementPrefix, Dictionary <string, string> attributeNameValues) { IXmlElement element = this.CreateElement(elementName, document, elementPrefix, manager); currentNode.AppendChild((IXmlNode)element); foreach (KeyValuePair <string, string> attributeNameValue in attributeNameValues) { string str = XmlConvert.EncodeName(attributeNameValue.Key); string prefix = MiscellaneousUtils.GetPrefix(attributeNameValue.Key); IXmlNode attribute = !string.IsNullOrEmpty(prefix) ? document.CreateAttribute(str, manager.LookupNamespace(prefix) ?? string.Empty, attributeNameValue.Value) : document.CreateAttribute(str, attributeNameValue.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) { string xmlValue = this.ConvertTokenToXmlValue(reader); if (xmlValue == null) { return; } element.AppendChild(document.CreateTextNode(xmlValue)); } else { if (reader.TokenType == JsonToken.Null) { return; } if (reader.TokenType != JsonToken.EndObject) { manager.PushScope(); this.DeserializeNode(reader, document, manager, (IXmlNode)element); manager.PopScope(); } manager.RemoveNamespace(string.Empty, manager.DefaultNamespace); } }
/// <summary> /// Executes the <see cref="ObjectSelector"/> rule against the <see cref="XNode"/>, /// importing matching objects. /// </summary> /// <param name="vault">The vault reference to use for processing the import.</param> /// <param name="node">The node to import data from.</param> /// <param name="objectSelector">The selector to execute.</param> /// <param name="xmlFile">The information about the XML file being imported.</param> /// <param name="parent">A parent object to create a relationship to, if appropriate.</param> /// <param name="xmlNamespaceManager">A namespace manager for using XML prefixes in XPath statements.</param> /// <returns>A list of files which were attached to the object, for deletion.</returns> public List <FileInfo> ImportXmlFile( Vault vault, XNode node, ObjectSelector objectSelector, FileInfo xmlFile = null, ObjVer parent = null, XmlNamespaceManager xmlNamespaceManager = null) { // Sanity. if (vault == null) { throw new ArgumentNullException(nameof(vault)); } if (null == node) { throw new ArgumentNullException(nameof(node)); } if (null == objectSelector) { throw new ArgumentNullException(nameof(objectSelector)); } if (string.IsNullOrWhiteSpace(objectSelector.XPathQuery)) { throw new ArgumentException("The XPath query for the object was empty", nameof(objectSelector)); } if (null == objectSelector.PropertySelectors) { throw new ArgumentException("The object selector contained no property selectors.", nameof(objectSelector)); } if (false == objectSelector.ObjectType.IsResolved) { throw new InvalidOperationException("The object selector object type is not resolved"); } if (false == objectSelector.Class.IsResolved) { throw new InvalidOperationException("The object selector class is not resolved"); } // Create a list of attached files (which can then be deleted later). var attachedFilesToDelete = new List <FileInfo>(); // Create the namespace manager. if (null != xmlNamespaceManager) { // Copy data from the other manager (so we don't accidentally affect other queries). var xmlNamespaceManager2 = new XmlNamespaceManager(new NameTable()); foreach (string prefix in xmlNamespaceManager) { // Don't add default. if (string.IsNullOrWhiteSpace(prefix)) { continue; } if (prefix == "xsi") { continue; } if (prefix == "xmlns") { continue; } // Add. xmlNamespaceManager2.AddNamespace(prefix, xmlNamespaceManager.LookupNamespace(prefix)); } xmlNamespaceManager = xmlNamespaceManager2; } else { xmlNamespaceManager = new XmlNamespaceManager(new NameTable()); } // Populate the namespace manager. if (null != objectSelector.XmlNamespaces) { foreach (var ns in objectSelector.XmlNamespaces) { // If the namespace manager already contains a prefix then remove it. string existingPrefix = xmlNamespaceManager.LookupPrefix(ns.Uri); if (false == string.IsNullOrEmpty(existingPrefix)) { xmlNamespaceManager.RemoveNamespace(existingPrefix, ns.Uri); } xmlNamespaceManager.AddNamespace(ns.Prefix, ns.Uri); } } // Find matching nodes. foreach (var matchingElement in node.XPathSelectElements(objectSelector.XPathQuery, xmlNamespaceManager)) { // Hold all the properties being read. var propertyValuesBuilder = new MFPropertyValuesBuilder(vault); // Add the class property value. propertyValuesBuilder.SetClass(objectSelector.Class.ID); // Retrieve the properties. foreach (var propertySelector in objectSelector.PropertySelectors) { // Sanity. if (string.IsNullOrWhiteSpace(propertySelector.XPathQuery)) { throw new ArgumentException("The object selector contained no property selectors.", nameof(objectSelector)); } if (false == propertySelector.PropertyDef.IsResolved) { throw new InvalidOperationException("The property value selector property definition is not resolved"); } // Retrieve the element for the property value. // var matchingPropertyElement = matchingElement // .XPathSelectElement(propertySelector.XPathQuery, xmlNamespaceManager); //if (null == matchingPropertyElement) // continue; // Find the property definition type. var propertyDefType = vault .PropertyDefOperations .GetPropertyDef(propertySelector.PropertyDef.ID) .DataType; // Check if it's lookup or multilookup var isLookup = ((propertyDefType == MFDataType.MFDatatypeMultiSelectLookup) || (propertyDefType == MFDataType.MFDatatypeLookup)); #region itterate XAttributes from XPath if (propertySelector.XPathQuery.Contains("@")) { List <int> listLookup = new List <int>(); IEnumerable matchingPropertyAttributes = (IEnumerable)matchingElement.XPathEvaluate(propertySelector.XPathQuery); foreach (System.Xml.Linq.XAttribute matchingPropertyAttribute in matchingPropertyAttributes) { string szValue = matchingPropertyAttribute.Value; if (propertyDefType == MFDataType.MFDatatypeBoolean) { propertyValuesBuilder.Add( propertySelector.PropertyDef.ID, propertyDefType, CastToBool(szValue)); } else if (propertyDefType == MFDataType.MFDatatypeDate) { szValue = $"{szValue} 00:00:00"; propertyValuesBuilder.Add( propertySelector.PropertyDef.ID, propertyDefType, szValue); } else if (isLookup) { var iLookupDef = (propertySelector.LookupOrValuelistStrategy == LookupOrValuelistStrategy.SearchLookup ? propertySelector.LookupObjectDef.ID : propertySelector.LookupValueListDef.ID); var iLookupItem = LookupRef(vault, iLookupDef, propertyDefType, propertySelector.SearchByLookupID, szValue, propertySelector.LookupOrValuelistStrategy); if (iLookupItem != -1) { listLookup.Add(iLookupItem); } } else { propertyValuesBuilder.Add( propertySelector.PropertyDef.ID, propertyDefType, szValue); } } // Lookup or MultiSelectLookup and found something if ((isLookup) && (listLookup.Count != 0)) { int[] arrLookupIDs = listLookup.ToArray(); propertyValuesBuilder.Add( propertySelector.PropertyDef.ID, propertyDefType, arrLookupIDs); } } #endregion else #region itterate XElements from XPath { List <int> listLookup = new List <int>(); var matchingPropertyElements = matchingElement.XPathSelectElements(propertySelector.XPathQuery); if (null == matchingPropertyElements) { continue; } // iterate found XElements foreach (var matchingPropertyElement in matchingPropertyElements) { if (null == matchingPropertyElement) { continue; } string szValue = matchingPropertyElement.Value; if (propertyDefType == MFDataType.MFDatatypeBoolean) { propertyValuesBuilder.Add( propertySelector.PropertyDef.ID, propertyDefType, CastToBool(szValue)); } else if (propertyDefType == MFDataType.MFDatatypeDate) { szValue = $"{szValue} 00:00:00"; propertyValuesBuilder.Add( propertySelector.PropertyDef.ID, propertyDefType, szValue); } else if (isLookup) { var iLookupDef = (propertySelector.LookupOrValuelistStrategy == LookupOrValuelistStrategy.SearchLookup ? propertySelector.LookupObjectDef.ID : propertySelector.LookupValueListDef.ID); var iLookupItem = LookupRef(vault, iLookupDef, propertyDefType, propertySelector.SearchByLookupID, szValue, propertySelector.LookupOrValuelistStrategy); if (iLookupItem != -1) { listLookup.Add(iLookupItem); } propertyValuesBuilder.AddLookup( propertySelector.PropertyDef.ID, szValue); } else { propertyValuesBuilder.Add( propertySelector.PropertyDef.ID, propertyDefType, szValue); } } // Lookup or MultiSelectLookup and found something if ((isLookup) && (listLookup.Count != 0)) { int[] arrLookupIDs = listLookup.ToArray(); propertyValuesBuilder.Add( propertySelector.PropertyDef.ID, propertyDefType, arrLookupIDs); } } #endregion // Add the property to the builder. //propertyValuesBuilder.Add( //propertySelector.PropertyDef.ID, //propertyDefType, //matchingPropertyElement.Value); } // Set the static values foreach (var staticPropertyValue in objectSelector.StaticPropertyValues ?? new List <StaticPropertyValue>()) { // Sanity. if (false == staticPropertyValue.PropertyDef.IsResolved) { throw new InvalidOperationException("The property value selector property definition is not resolved"); } // Find the property definition type. var propertyDefType = vault .PropertyDefOperations .GetPropertyDef(staticPropertyValue.PropertyDef.ID) .DataType; // Add the property to the builder. propertyValuesBuilder.Add( staticPropertyValue.PropertyDef.ID, propertyDefType, staticPropertyValue.Value); } // Create a reference to the parent? if (null != parent) { // If the property definition to use was configured then use that. if (true == objectSelector.ParentRelationshipPropertyDef?.IsResolved) { // Check that this property is a list and is for the correct object type. var parentRelationshipPropertyDef = vault .PropertyDefOperations .GetPropertyDef(objectSelector.ParentRelationshipPropertyDef.ID); if (false == parentRelationshipPropertyDef.BasedOnValueList || parentRelationshipPropertyDef.ValueList != parent.Type) { throw new InvalidOperationException( $"The property def {parentRelationshipPropertyDef.Name} ({parentRelationshipPropertyDef.ID}) is not based on value list {parent.Type}."); } // Use the configured property definition. propertyValuesBuilder.Add( parentRelationshipPropertyDef.ID, parentRelationshipPropertyDef.DataType, parent.ID); } else { // Retrieve data about the parent object type. var parentObjectType = vault .ObjectTypeOperations .GetObjectType(parent.Type); // Retrieve data about the child object type. var childObjectType = vault .ObjectTypeOperations .GetObjectType(objectSelector.ObjectType.ID); // Is there an owner for this child type? if (childObjectType.HasOwnerType) { // Use the "owner" property definition. propertyValuesBuilder.Add( parentObjectType.OwnerPropertyDef, MFDataType.MFDatatypeLookup, parent.ID); } else { // Use the default property definition. propertyValuesBuilder.Add( parentObjectType.DefaultPropertyDef, MFDataType.MFDatatypeMultiSelectLookup, parent.ID); } } } // Create a container for any attached files. var sourceObjectFiles = new SourceObjectFiles(); // Should we attach the file to this object? if (objectSelector.AttachFileToThisObject) { // Locate the files to retrieve. sourceObjectFiles = this.FindFilesToAttach(objectSelector, xmlFile, matchingElement, xmlNamespaceManager); // If we were supposed to attach a file but no files were found then throw an exception. if (objectSelector.AttachedFileConfiguration?.FileNotFoundHandlingStrategy == FileNotFoundHandlingStrategy.Fail && 0 == sourceObjectFiles.Count) { throw new InvalidOperationException("Attached file expected but not found."); } if (objectSelector.AttachedFileConfiguration?.AttachedFileHandlingStrategy == AttachedFileHandlingStrategy.AttachToCurrentObject) { // Retrieve information about the object type from the vault. var objectType = vault .ObjectTypeOperations .GetObjectType(objectSelector.ObjectType.ID); // If the object type cannot have files but we are meant to attach a file, then fail. if (false == objectType.CanHaveFiles) { throw new InvalidOperationException( $"The object type {objectType.NameSingular} cannot have files, but the configuration states to attach a file."); } } } // Which source object files should we use for the new object? var sourceObjectFilesForNewObject = objectSelector.AttachedFileConfiguration?.AttachedFileHandlingStrategy == AttachedFileHandlingStrategy.AttachToCurrentObject ? sourceObjectFiles : new SourceObjectFiles(); // Add the object to the vault. var createdObject = vault .ObjectOperations .CreateNewObjectEx( objectSelector.ObjectType.ID, propertyValuesBuilder.Values, sourceObjectFilesForNewObject, SFD: objectSelector.ObjectType.ID == (int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument && sourceObjectFilesForNewObject.Count == 1 ); // The files which need to be deleted. attachedFilesToDelete.AddRange( sourceObjectFiles .Cast <SourceObjectFile>() .Select(sof => new FileInfo(sof.SourceFilePath)) ); // Are there any related objects (e.g. children) to create? foreach (var childObjectSelector in objectSelector.ChildObjectSelectors) { attachedFilesToDelete.AddRange(this.ImportXmlFile(vault, matchingElement, childObjectSelector, xmlFile: xmlFile, parent: createdObject.ObjVer, xmlNamespaceManager: xmlNamespaceManager)); } // Clean up the collections we were using. propertyValuesBuilder = new MFPropertyValuesBuilder(vault); // Handle creating a new object for the file. if ( objectSelector.AttachFileToThisObject && objectSelector.AttachedFileConfiguration?.AttachedFileHandlingStrategy == AttachedFileHandlingStrategy.CreateNewObject) { // Set the static values foreach (var staticPropertyValue in objectSelector.AttachedFileConfiguration?.StaticPropertyValues ?? new List <StaticPropertyValue>()) { // Sanity. if (false == staticPropertyValue.PropertyDef.IsResolved) { throw new InvalidOperationException("The property value selector property definition is not resolved"); } // Find the property definition type. var propertyDefType = vault .PropertyDefOperations .GetPropertyDef(staticPropertyValue.PropertyDef.ID) .DataType; // Add the property to the builder. propertyValuesBuilder.Add( staticPropertyValue.PropertyDef.ID, propertyDefType, staticPropertyValue.Value); } // Add the class property value. propertyValuesBuilder.SetClass(objectSelector.AttachedFileConfiguration.Class.ID); // Add a reference from this new object to the one we created earlier. { // Retrieve data about the parent object type. var parentObjectType = vault .ObjectTypeOperations .GetObjectType(createdObject.ObjVer.Type); // Set the relationship. propertyValuesBuilder.Add( parentObjectType.DefaultPropertyDef, MFDataType.MFDatatypeMultiSelectLookup, createdObject.ObjVer.ID); } // Add the object to the vault. var createdDocumentObject = vault .ObjectOperations .CreateNewObjectEx( objectSelector.AttachedFileConfiguration.ObjectType.ID, propertyValuesBuilder.Values, sourceObjectFiles, SFD: objectSelector.AttachedFileConfiguration.ObjectType.ID == (int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument && sourceObjectFiles.Count == 1 ); } } // Return the files to remove. return(attachedFilesToDelete); }
// Test adding items to a namespace manager. public void TestXmlNamespaceManagerAdd() { NameTable table = new NameTable(); XmlNamespaceManager ns = new XmlNamespaceManager(table); // Test exception behaviour. try { ns.AddNamespace(null, "uri"); Fail("Add (1)"); } catch(ArgumentNullException) { // Success } try { ns.AddNamespace("prefix", null); Fail("Add (2)"); } catch(ArgumentNullException) { // Success } try { ns.AddNamespace("xml", "uri"); Fail("Add (3)"); } catch(ArgumentException) { // Success } try { ns.AddNamespace("xmlns", "uri"); Fail("Add (4)"); } catch(ArgumentException) { // Success } try { // Work around intern'ed string handling in the engine. ns.AddNamespace(String.Concat("xml", "ns"), "uri"); Fail("Add (5)"); } catch(ArgumentException) { // Success } // Try changing the default namespace. ns.AddNamespace("", "defuri"); AssertEquals("Add (6)", "defuri", ns.LookupNamespace("")); AssertEquals("Add (7)", "defuri", ns.DefaultNamespace); AssertEquals("Add (8)", "", ns.LookupPrefix("defuri")); // Try changing some other namespace. ns.AddNamespace("foo", "uri"); AssertEquals("Add (9)", "uri", ns.LookupNamespace("foo")); AssertEquals("Add (10)", "foo", ns.LookupPrefix("uri")); // Make sure that the standard are still set to their // correct values after the modifications above. AssertEquals("Add (11)", "http://www.w3.org/XML/1998/namespace", ns.LookupNamespace("xml")); AssertEquals("Add (12)", "http://www.w3.org/2000/xmlns/", ns.LookupNamespace("xmlns")); AssertEquals("Add (13)", "defuri", ns.LookupNamespace("")); }
public static string ParsificazioneXmlCasa(string xmlResponse, UserProfile user, string codiceCompagnia, int proposalCode, bool cancellaNodoMessaggiErrore = false) { List <string> _listaCodiciFattoreCASA_RMA = new List <string>() { "2CNPRO", // codice proposta (full/furto/.../...) "2FABPA", // fabbricato di proprietà o affitto "2SUPMQ", // superficie mq "2TIFAB", // tipo di fabbricato "2QLTAB", // qualità delle finiture "2COMUN", // comune "2PROVI", // provincia "2CAP", // cap "2TIDIM", // tipo dimora "4ZTEC1", // zona territoriale "_2UPIS", // cap + istat }; List <string> _listaCodiciFattoreCASA_ITA = new List <string>() { "3SUPEM", // superficie mq "2CAPQQ", // CAP "2CNTRP", // contraente della polizza "2ABWEB", // tipo abitazione "2QLTAB", // qualità delle finiture }; string dataDecorrenza = DateTime.Now.AddMonths(2).ToString("dd/MM/yyyy"); string xml = string.Empty; List <string> listaCodiciFattorePerCompagnia = codiceCompagnia == "1" ? _listaCodiciFattoreCASA_RMA : _listaCodiciFattoreCASA_ITA; XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlResponse); if (doc.FirstChild.NodeType == XmlNodeType.XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } #region Namespace xml XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); if (doc.DocumentElement.Attributes["xmlns:S"] != null) { string s = doc.DocumentElement.Attributes["xmlns:S"].Value; nsmgr.AddNamespace("S", s); } XmlNode nodeRoot = doc.SelectSingleNode("S:Envelope/S:Body", nsmgr); if (nodeRoot != null) { XmlNode nodeNamespace = nodeRoot.LastChild; if (nodeNamespace.Attributes["xmlns:ns3"] != null) { string ns3 = nodeNamespace.Attributes["xmlns:ns3"].Value; nsmgr.AddNamespace("ns3", ns3); } if (nodeNamespace.Attributes["xmlns:ns2"] != null) { string ns2 = nodeNamespace.Attributes["xmlns:ns2"].Value; nsmgr.AddNamespace("ns2", ns2); } if (nodeNamespace.Attributes["xmlns:ns7"] != null) { string ns7 = nodeNamespace.Attributes["xmlns:ns7"].Value; nsmgr.AddNamespace("ns7", ns7); } if (nodeNamespace.Attributes["xmlns:ns9"] != null) { string ns9 = nodeNamespace.Attributes["xmlns:ns9"].Value; nsmgr.AddNamespace("ns9", ns9); } } #endregion // nodo quote principale XmlNode nodoQuote = null; XmlNode nodoInfoRGI = null; string stringaQuote = "S:Envelope/S:Body/{0}:{1}/return/{0}:quote"; XmlNodeList nodoQuoteList = doc.SelectNodes(string.Format(stringaQuote, "ns3", "getSHPQuoteResponse"), nsmgr); if (nodoQuoteList != null & nodoQuoteList.Count <= 0) { nodoQuoteList = doc.SelectNodes(string.Format(stringaQuote, "ns3", "pricingSHPQuoteResponse"), nsmgr); } if (nodoQuoteList != null & nodoQuoteList.Count <= 0) { nodoQuoteList = doc.SelectNodes(string.Format(stringaQuote, "ns2", "getSHPQuoteResponse"), nsmgr); } if (nodoQuoteList != null & nodoQuoteList.Count <= 0) { nodoQuoteList = doc.SelectNodes(string.Format(stringaQuote, "ns2", "pricingSHPQuoteResponse"), nsmgr); } if (nodoQuoteList != null & nodoQuoteList.Count > 0) { nodoQuote = nodoQuoteList[0]; nodoInfoRGI = nodoQuote.NextSibling; if (cancellaNodoMessaggiErrore) { // RIMUOVO IL PRECEDENTE ERRORE SE C'E' STATO XmlNode nodoErrore = nodoQuote.SelectSingleNode("ns7:messages", nsmgr); if (nodoErrore != null) { nodoErrore.RemoveAll(); } } } #region Iniettando la data decorrenza polizza if (string.IsNullOrEmpty(dataDecorrenza) == false) { XmlNode nodoEffectiveDate = nodoQuote.SelectSingleNode("ns7:effectiveDate", nsmgr); XmlNode nodoData = null; if (nodoEffectiveDate != null) { nodoData = nodoEffectiveDate.ChildNodes[0]; string dataEffective = string.Format("{0}-{1}-{2}T00:00:00.000+0{3}:00", dataDecorrenza.Split('/')[2], (dataDecorrenza.Split('/')[1].Length == 1) ? "0" + dataDecorrenza.Split('/')[1] : dataDecorrenza.Split('/')[1], (dataDecorrenza.Split('/')[0].Length == 1) ? "0" + dataDecorrenza.Split('/')[0] : dataDecorrenza.Split('/')[0], TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalHours.ToString()); if (nodoData != null) { nodoData.InnerText = dataEffective; } else { nodoData = doc.CreateElement("ns2:data", nsmgr.LookupNamespace("ns2")); nodoData.InnerText = dataEffective; nodoEffectiveDate.AppendChild(nodoData); } } } #endregion XmlNodeList listaNodiFattori = nodoQuote.SelectNodes("ns7:product/ns9:assets/ns9:instances/ns9:factors", nsmgr); if (listaNodiFattori != null & listaNodiFattori.Count > 0) { string codiceFattore = string.Empty; XmlNode nodoValue; XmlNode nodoManuallySet; XmlNode nodoBooleanManuallySet; #region Iniettando la data di policyExpirationDate con data attuale + 1 anno // Chat con Mirko del 24 settembre 2018 /* * di default è impostata a 2 giorni della data effetto * es: data effetto 24/09/2018 data scadenza: 26/09/2018 * * solo per il casa, bisognerebbe impostarla ad un anno dalla data effetto */ XmlNode nodoPolicyExpirationDate = nodoQuote.SelectSingleNode("ns7:policyExpirationDate", nsmgr); XmlNode nodoDataPol = null; if (nodoPolicyExpirationDate != null) { // nodoDataPol = nodoPolicyExpirationDate.SelectSingleNode("ns2:data", nsmgr); nodoDataPol = nodoPolicyExpirationDate.ChildNodes[0]; string dataPolicy = string.Format("{0}-{1}-{2}T00:00:00+0{3}:00", DateTime.Now.AddYears(1).Year.ToString(), (DateTime.Now.Month.ToString().Length == 1) ? "0" + DateTime.Now.Month.ToString() : DateTime.Now.Month.ToString(), (DateTime.Now.Day.ToString().Length == 1) ? "0" + DateTime.Now.Day : DateTime.Now.Day.ToString(), TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalHours.ToString()); if (nodoDataPol != null) { nodoDataPol.InnerText = dataPolicy; } else { nodoDataPol = doc.CreateElement("ns2:data", nsmgr.LookupNamespace("ns2")); nodoDataPol.InnerText = dataPolicy; nodoPolicyExpirationDate.AppendChild(nodoDataPol); } } #endregion #region Iniettando nodo requesterEMailAddress per gestione tracking preventivi Casa/Viaggi (IM9950680 RGI). Mail del 02/01/2019 ore 11:07 da Mirko Rizzo XmlNode nodoRequesterEmail = nodoQuote.SelectSingleNode("ns7:requesterEMailAddress", nsmgr); if (nodoRequesterEmail == null) { nodoRequesterEmail = doc.CreateElement("ns7:requesterEMailAddress", nsmgr.LookupNamespace("ns7")); nodoRequesterEmail.InnerText = user.Email; nodoQuote.AppendChild(nodoRequesterEmail); } else { nodoRequesterEmail.InnerText = user.Email; } #endregion #region " Iniettando i valori del form " foreach (XmlNode nodoChildFactor in listaNodiFattori) { // per ogni elemento attivo del form Step1 bisogna verificare l'associazione con il codice che si sta esaminando dell'xml e nel nodo "value" settare il valore corrispondente codiceFattore = nodoChildFactor.SelectSingleNode("ns9:code", nsmgr).InnerText; if (listaCodiciFattorePerCompagnia.Contains(codiceFattore)) { nodoValue = nodoChildFactor.SelectSingleNode("ns9:value", nsmgr); if (codiceFattore == "2CNPRO") { continue; } nodoManuallySet = nodoChildFactor.SelectSingleNode("ns9:manuallySet", nsmgr); if (nodoManuallySet != null) { // nodoBooleanManuallySet = nodoManuallySet.SelectSingleNode("ns2:boolean", nsmgr); nodoBooleanManuallySet = nodoManuallySet.ChildNodes[0]; if (nodoBooleanManuallySet == null) { nodoBooleanManuallySet = nodoManuallySet.SelectSingleNode("ns3:boolean", nsmgr); } if (nodoBooleanManuallySet != null) { nodoBooleanManuallySet.InnerText = "true"; } } switch (codiceFattore) { case "2FABPA": // Fabbricato di proprietà o affitto if (nodoValue != null) { nodoValue.InnerText = user.PA; } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.PA; nodoChildFactor.AppendChild(nodoValue); } break; case "2SUPMQ": // Superficie fabbricato (mq commerciali) case "3SUPEM": if (nodoValue != null) { nodoValue.InnerText = user.MQ.Replace("mq", string.Empty); } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.MQ.Replace("mq", string.Empty); nodoChildFactor.AppendChild(nodoValue); } break; case "2TIFAB": // Tipo di fabbricato if (nodoValue != null) { nodoValue.InnerText = user.Fabbricato; } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.Fabbricato; nodoChildFactor.AppendChild(nodoValue); } break; case "2QLTAB": // Qualità delle finiture if (nodoValue != null) { nodoValue.InnerText = user.Finiture; } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.Finiture; nodoChildFactor.AppendChild(nodoValue); } break; case "2COMUN": // Comune if (nodoValue != null) { nodoValue.InnerText = user.Comune; } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.Comune; nodoChildFactor.AppendChild(nodoValue); } break; case "2PROVI": // Provincia (stesso valore di zona territoriale) if (nodoValue != null) { nodoValue.InnerText = user.ProvRes; } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.ProvRes; nodoChildFactor.AppendChild(nodoValue); } break; case "2CAP": // CAP case "2CAPQQ": if (nodoValue != null) { nodoValue.InnerText = user.Cap; } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.Cap; nodoChildFactor.AppendChild(nodoValue); } break; case "2TIDIM": // Tipo Dimora if (nodoValue != null) { nodoValue.InnerText = user.AS; } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.AS; nodoChildFactor.AppendChild(nodoValue); } break; case "4ZTEC1": // Zona territoriale if (nodoValue != null) { nodoValue.InnerText = user.ProvRes; } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.ProvRes; nodoChildFactor.AppendChild(nodoValue); } break; case "_2UPIS": // CAP + Codice Istat comune if (nodoValue != null) { nodoValue.InnerText = user.Cap + user.Istat; // Mirko: il cap generico della città concatenato l'ISTAT della città (per esempio Torino: 10100001272) } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.Istat; nodoChildFactor.AppendChild(nodoValue); } break; case "2CNTRP": // Contraente della polizza if (nodoValue != null) { nodoValue.InnerText = user.PA; } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.PA; nodoChildFactor.AppendChild(nodoValue); } break; case "2ABWEB": // Tipo abitazione if (nodoValue != null) { nodoValue.InnerText = user.AS; } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.AS; nodoChildFactor.AppendChild(nodoValue); } break; } } } #endregion #region " Inietto valore codice proposta e nient'altro " foreach (XmlNode nodoChildFactor in listaNodiFattori) { codiceFattore = nodoChildFactor.SelectSingleNode("ns9:code", nsmgr).InnerText; if (codiceFattore != "2CNPRO") { continue; } else { nodoManuallySet = nodoChildFactor.SelectSingleNode("ns9:manuallySet", nsmgr); if (nodoManuallySet != null) { //nodoBooleanManuallySet = nodoManuallySet.SelectSingleNode("ns2:boolean", nsmgr); nodoBooleanManuallySet = nodoManuallySet.ChildNodes[0]; if (nodoBooleanManuallySet == null) { nodoBooleanManuallySet = nodoManuallySet.SelectSingleNode("ns3:boolean", nsmgr); } if (nodoBooleanManuallySet != null) { nodoBooleanManuallySet.InnerText = "true"; } } nodoValue = nodoChildFactor.SelectSingleNode("ns9:value", nsmgr); if (nodoValue != null) { nodoValue.InnerText = Convert.ToString(proposalCode); } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = Convert.ToString(proposalCode); nodoChildFactor.AppendChild(nodoValue); } break; } } #endregion #region Inietto informazione per RGI cambio formula (chat con Mirko) /* * <ns2:serviceInfo> * ... <- qui c'è il resto del serviceInfo * <ns3:properties> * <ns3:chiave>CAMBIO_FORMULA</ns3:chiave> * <ns3:valore>1</ns3:valore> * </ns3:properties> * </ns2:serviceInfo> */ if (nodoInfoRGI != null) { bool esiste = false; XmlNode nodoProperties = nodoInfoRGI.SelectSingleNode("ns2:properties", nsmgr); foreach (XmlNode nodoProp in nodoInfoRGI.ChildNodes) { if (nodoProp.LocalName == "properties") { XmlNode nodoChiave = nodoProp.FirstChild; XmlNode nodoValore = nodoProp.LastChild; if (nodoChiave != null) { if (nodoChiave.InnerText == "CAMBIO_FORMULA") { esiste = true; if (nodoValore != null) { nodoValore.InnerText = "1"; } break; } } } } if (esiste == false) { XmlElement nodoPropertiesNuovo = doc.CreateElement("ns2:properties", nsmgr.LookupNamespace("ns2")); XmlElement nodoChiave = doc.CreateElement("ns2:chiave", nsmgr.LookupNamespace("ns2")); XmlElement nodoValore = doc.CreateElement("ns2:valore", nsmgr.LookupNamespace("ns2")); nodoChiave.InnerText = "CAMBIO_FORMULA"; nodoValore.InnerText = "1"; nodoPropertiesNuovo.AppendChild(nodoChiave); nodoPropertiesNuovo.AppendChild(nodoValore); nodoInfoRGI.AppendChild(nodoPropertiesNuovo); } } #endregion #region Iniettando la data di policyExpirationDate con data decorrenza polizza (scelta dall'utente) + 1 anno nodoPolicyExpirationDate = nodoQuote.SelectSingleNode("ns7:policyExpirationDate", nsmgr); nodoDataPol = null; if (nodoPolicyExpirationDate != null) { nodoDataPol = nodoPolicyExpirationDate.ChildNodes[0]; String dataPolicy = String.Format("{0}-{1}-{2}T00:00:00+0{3}:00", DateTime.Parse(dataDecorrenza).AddYears(1).Year.ToString(), (DateTime.Parse(dataDecorrenza).Month.ToString().Length == 1) ? "0" + DateTime.Parse(dataDecorrenza).Month.ToString() : DateTime.Parse(dataDecorrenza).Month.ToString(), (DateTime.Parse(dataDecorrenza).Day.ToString().Length == 1) ? "0" + DateTime.Parse(dataDecorrenza).Day : DateTime.Parse(dataDecorrenza).Day.ToString(), TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Parse(dataDecorrenza)).TotalHours.ToString()); if (nodoDataPol != null) { nodoDataPol.InnerText = dataPolicy; } else { nodoDataPol = doc.CreateElement("ns2:data", nsmgr.LookupNamespace("ns2")); nodoDataPol.InnerText = dataPolicy; nodoPolicyExpirationDate.AppendChild(nodoDataPol); } } #endregion } xml = doc.InnerXml; return(xml); }
public static void ApplyFixupFile(this XDocument document, string filename) { if (document == null) { throw new ArgumentNullException("document"); } if (filename == null) { throw new ArgumentNullException("filename"); } // Helpful for creating a .girfixup that skips everything // foreach (var e in document.Element (gi + "repository").Element (gi + "namespace").Elements ()) { // Console.WriteLine ($"chattr \"skip\" \"\" \"1\" \"gi:repository/gi:namespace/gi:{e.Name.LocalName}[@name='{e.Attribute ("name").Value}']\""); // } var quoteCount = 0; var lastCharWasEscape = false; var builder = new StringBuilder(); string command = null; var parameters = new List <string> (); var commands = new List <Tuple <string, List <string> > > (); var lineNo = 0; foreach (var line in File.ReadLines(filename)) { lineNo++; if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#", StringComparison.Ordinal)) { // ignore empty lines and comments continue; } var charNo = 0; if (!lastCharWasEscape) { // if the previous line did not end with a backslash, then reset for next command quoteCount = 0; builder.Clear(); command = null; parameters = new List <string> (); } lastCharWasEscape = false; foreach (var c in line) { charNo++; // read the command - it is not quoted if (command == null) { if (char.IsWhiteSpace(c)) { command = builder.ToString(); builder.Clear(); } else { builder.Append(c); } continue; } // then read all of the parameters - they are all in quotes if (c == '"' && !lastCharWasEscape) { quoteCount++; if ((quoteCount % 2) == 0) { parameters.Add(builder.ToString()); builder.Clear(); } } else { if ((quoteCount % 2) == 0) { if (!char.IsWhiteSpace(c) && (c != '\\')) { throw new Exception(string.Format("Expecting whitespace at {0}:{1}", lineNo, charNo)); } } else { builder.Append(c); } } lastCharWasEscape = (c == '\\'); } if (lastCharWasEscape) { continue; } int paramCount; switch (command) { case "addelement": case "chelement": case "move": paramCount = 2; break; case "chattr": paramCount = 4; break; default: throw new Exception(string.Format("Unknown command '{0}'", command)); } if (parameters.Count != paramCount) { throw new Exception(string.Format("{0} command on line {1} requires {3} parameters", command, lineNo, paramCount)); } commands.Add(new Tuple <string, List <string> > (command, parameters)); } if (commands.Count == 0) { Console.Error.WriteLine("Warning: File '{0}' is empty.", filename); } foreach (var tuple in commands) { command = tuple.Item1; parameters = tuple.Item2; switch (command) { case "addelement": var newElement = parseElement(parameters [0]); var addParent = document.XPathSelectElement(parameters [1], Manager); if (addParent == null) { Console.Error.WriteLine("Could not find element at '{0}'", parameters [1]); break; } addParent.Add(newElement); break; case "chattr": var attributeParts = parameters [0].Split(':'); var localName = attributeParts [0]; var @namespace = XNamespace.None; if (attributeParts.Length > 1) { localName = attributeParts [1]; @namespace = (XNamespace)Manager.LookupNamespace(attributeParts [0]); } var chattrElements = document.XPathSelectElements(parameters[3], Manager).ToList(); if (chattrElements.Count == 0) { Console.Error.WriteLine("Could not find any elements matching '{0}'", parameters[3]); break; } foreach (var element in chattrElements) { var attribute = element.Attribute(@namespace + localName); var oldValue = attribute == null ? string.Empty : attribute.Value; var newValue = parameters[1] == string.Empty ? parameters[2] : Regex.Replace(oldValue, parameters[1], parameters[2]); element.SetAttributeValue(@namespace + localName, newValue); } break; case "chelement": var elementParts = parameters [0].Split(':'); var elementLocalName = elementParts [0]; var elementNamespace = XNamespace.None; if (elementParts.Length > 1) { elementLocalName = elementParts [1]; elementNamespace = (XNamespace)Manager.LookupNamespace(elementParts [0]); } var elementsToChange = document.XPathSelectElements(parameters [1], Manager); if (elementsToChange == null) { Console.Error.WriteLine("Could not find elements matching '{0}'", parameters [1]); break; } foreach (var element in elementsToChange) { element.Name = elementNamespace + elementLocalName; } break; case "move": var moveElements = document.XPathSelectElements(parameters[0], Manager).ToList(); if (moveElements.Count == 0) { Console.Error.WriteLine("Could not find any elements matching '{0}'", parameters[0]); } var moveParent = document.XPathSelectElement(parameters[1], Manager); if (moveParent == null) { Console.Error.WriteLine("Could not find element at '{0}'", parameters[1]); break; } foreach (var element in moveElements) { element.Remove(); moveParent.Add(element); } break; } } }
public static XmlNode SetTextInElement(XmlElement element, string name, string text, XmlNamespaceManager nsMgr) { if (element == null) { throw new Exception("Passed in a null node, which should never happen."); } XmlElement newChild = (XmlElement)element.SelectSingleNode("descendant::ns1:" + name, nsMgr); if (newChild == null) { newChild = (XmlElement)element.AppendChild(element.OwnerDocument.CreateElement(name, nsMgr.LookupNamespace("ns1"))); } newChild.InnerText = text; return(element.AppendChild(newChild)); }
XmlNode FillXmlByDatable(XmlNode parent, DataSet ds, int dtindex, List <TableGuider> guds) { if (ds.Tables.Count <= dtindex) { throw new Exception("Jdy:数据集超出索引!"); } if (guds.Count <= dtindex) { throw new Exception("Jdy:Schema配置超出索引!"); } TableGuider tg = guds[dtindex]; TableGuider pretg = null; if (dtindex > 0) { pretg = guds[dtindex - 1]; } if (tg.TableName == null || tg.TableName.Trim().Length == 0) { throw new Exception("Jdy:Schema配置Json超出索引!"); } DataTable dt = ds.Tables[dtindex]; string RepeatItem = guds[dtindex].TableName; XmlDocument doc = parent.OwnerDocument; if (doc == null) { doc = parent as XmlDocument; } XmlNamespaceManager xmlm = new XmlNamespaceManager(doc.NameTable); xmlm.AddNamespace("json", "http://james.newtonking.com/projects/json");//添加命名空间 string filter = ""; if (pretg == null || pretg.KeyValue == null) { filter = "1=1"; } else { filter = string.Format("{0}='{1}'", pretg.NextRef, pretg.KeyValue); } DataRow[] drs = dt.Select(filter); for (int i = 0; i < drs.Length; i++) { XmlNode node = doc.CreateElement(RepeatItem, xmlm.LookupNamespace("json")); XmlAttribute att = doc.CreateAttribute("json:Array", xmlm.LookupNamespace("json")); att.Value = "true"; node.Attributes.Append(att); //XmlUtil.AddAttribute(node, "json:Array", "true"); string keyval = null; for (int j = 0; j < dt.Columns.Count; j++) { string col = dt.Columns[j].ColumnName; string val = drs[i][col].ToString(); XmlNode subnode = doc.CreateElement(col); subnode.InnerText = val; if (tg.Key == null || tg.Key.Trim().Length < dtindex + 1) { node.AppendChild(subnode); continue; } if (tg.Key != null && tg.Key == col.ToLower()) { keyval = val; } node.AppendChild(subnode); } if (keyval == null && string.IsNullOrEmpty(tg.Key))//没遇到主键,下一行 { parent.AppendChild(node); continue; } int NextIdx = dtindex + 1; if (ds.Tables.Count <= NextIdx || guds.Count <= NextIdx) { parent.AppendChild(node); continue; } guds[NextIdx].KeyValue = keyval; node = FillXmlByDatable(node, ds, NextIdx, guds); parent.AppendChild(node); } return(parent); }
protected string GetSpecialValue(XmlReader reader, string ns, string field) { return(GetSpecialValue(reader, ns, field, _nameSpaceManager.LookupNamespace(ns))); }
public void Import(string FilenameToLoad) { Log("Message", "Import", String.Format("File : {0}", FilenameToLoad)); String InterlStoreFilename = this.Filename; //Instantiate a new document to hold the ILR data this.ILRFile = new XmlDocument(); //Get a namespace manager from the XML document NSMgr = new XmlNamespaceManager(ILRFile.NameTable); NSMgr.AddNamespace("ia", CurrentNameSpace); this.ILRFile.AppendChild(this.ILRFile.CreateElement("Message", NSMgr.LookupNamespace("ia"))); // Clear Old Learner and Old LearnerDestinationandProgression Records this.LearnerList.Clear(); this.LearnerDestinationandProgressionList.Clear(); Message importMessage = new Message(); System.IO.FileInfo fi = new System.IO.FileInfo(FilenameToLoad); if (fi.Name.Contains("-" + CurrentYear.ToString() + "-")) { Log("Message", "Import", String.Format("Current Year : {0}", CurrentYear)); this.Load(FilenameToLoad); } else if (fi.Name.Contains("-" + (CurrentYear - 101).ToString() + "-")) { Log("Message", "Import", String.Format("Load Previous Year ILR : {0}", (CurrentYear - 101))); importMessage.LoadPreviousYearILR(FilenameToLoad, _logFileName); XmlNode headerNode = this.ILRFile.SelectSingleNode("/ia:Message/ia:Header", NSMgr); if (headerNode == null) { headerNode = this.ILRFile.CreateElement("Header", NSMgr.LookupNamespace("ia")); } if (this.ILRFile.DocumentElement.HasChildNodes) { this.ILRFile.DocumentElement.InsertBefore(headerNode, this.ILRFile.DocumentElement.FirstChild); } else { this.ILRFile.DocumentElement.AppendChild(headerNode); } this.Header = new ILR.Header(headerNode, NSMgr); //Find the LearningProvider node XmlNode learningProviderNode = this.ILRFile.SelectSingleNode("/ia:Message/ia:LearningProvider", NSMgr); //Find the Learner nodes XmlNodeList learnerNodes = this.ILRFile.SelectNodes("/ia:Message/ia:Learner", NSMgr); //If we have no LearningProvider node create one in the correct place if (learningProviderNode == null) { learningProviderNode = this.ILRFile.CreateElement("LearningProvider", NSMgr.LookupNamespace("ia")); if (learnerNodes.Count == 0) { this.ILRFile.DocumentElement.AppendChild(learningProviderNode); } else { this.ILRFile.DocumentElement.InsertBefore(learningProviderNode, learnerNodes.Item(0)); } } this.LearningProvider = new ILR.LearningProvider(learningProviderNode, NSMgr); this.LearningProvider.UKPRN = importMessage.LearningProvider.UKPRN; var x = importMessage.LearnerList.Where(l => l.HasContinuingAims); //var x = importMessage.LearnerList.ToList(); var y = importMessage.LearnerDestinationandProgressionList.Where(ldp => ldp.HasCurrentDPOutcomes); importMessage = null; foreach (Learner learner in x) { try { XmlNode newNode = ILRFile.CreateElement("Learner", NSMgr.LookupNamespace("ia")); Learner newInstance = new Learner(learner, newNode, NSMgr); newInstance.Message = this; LearnerList.Add(newInstance); AppendToLastOfNodeNamed(newNode, newNode.Name); newInstance.ResequenceAimSeqNumber(); Log("Message", "Import", String.Format("Learner {0} : {0}", LearnerList.Count, newInstance.LearnRefNumber)); } catch (Exception el) { Log("Message", "Import", String.Format("Error Loading Learner : {0}", el.Message)); Console.WriteLine(String.Format("Learern Ref:{0}", learner.LearnRefNumber)); } } foreach (LearnerDestinationandProgression learnerDestinationandProgression in y) { XmlNode newNode = ILRFile.CreateElement("LearnerDestinationandProgression", NSMgr.LookupNamespace("ia")); LearnerDestinationandProgression newInstance = new LearnerDestinationandProgression(learnerDestinationandProgression, newNode, NSMgr); newInstance.Message = this; LearnerDestinationandProgressionList.Add(newInstance); AppendToLastOfNodeNamed(newNode, newNode.Name); Log("Message", "Import", String.Format("LearnerDestinationandProgressionList {0} : {0}", LearnerDestinationandProgressionList.Count, newInstance.LearnRefNumber)); } importMessage = null; } else { throw (new Exception("Unable to identify Year from filename. Confirm the file name matchesd the ILR Specification.")); } this.Filename = InterlStoreFilename; Save(); GC.Collect(); }
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Write(XmlWriter writer, XmlNamespaceManager namespaceManager) { XmlSerializer serializer = new XmlSerializer(typeof(XmlSchema)); XmlSerializerNamespaces ns; if (namespaceManager != null) { ns = new XmlSerializerNamespaces(); bool ignoreXS = false; if (this.Namespaces != null) { //User may have set both nsManager and Namespaces property on the XmlSchema object ignoreXS = this.Namespaces.Namespaces["xs"] != null || this.Namespaces.Namespaces.ContainsValue(XmlReservedNs.NsXs); } if (!ignoreXS && namespaceManager.LookupPrefix(XmlReservedNs.NsXs) == null && namespaceManager.LookupNamespace("xs") == null ) { ns.Add("xs", XmlReservedNs.NsXs); } foreach(string prefix in namespaceManager) { if (prefix != "xml" && prefix != "xmlns") { ns.Add(prefix, namespaceManager.LookupNamespace(prefix)); } } } else if (this.Namespaces != null && this.Namespaces.Count > 0) { Hashtable serializerNS = this.Namespaces.Namespaces; if (serializerNS["xs"] == null && !serializerNS.ContainsValue(XmlReservedNs.NsXs)) { //Prefix xs not defined AND schema namespace not already mapped to a prefix serializerNS.Add("xs", XmlReservedNs.NsXs); } ns = this.Namespaces; } else { ns = new XmlSerializerNamespaces(); ns.Add("xs", XmlSchema.Namespace); if (targetNs != null && targetNs.Length != 0) { ns.Add("tns", targetNs); } } serializer.Serialize(writer, this, ns); }
// Check the "RemoveNamespace" method. public void TestXmlNamespaceManagerRemove() { NameTable table = new NameTable(); XmlNamespaceManager ns = new XmlNamespaceManager(table); // Test the exception behaviour. try { ns.AddNamespace(null, "uri"); Fail("Remove (1)"); } catch(ArgumentNullException) { // Success } try { ns.AddNamespace("prefix", null); Fail("Remove (2)"); } catch(ArgumentNullException) { // Success } // Cannot remove standard namespaces. ns.RemoveNamespace ("xml", "http://www.w3.org/XML/1998/namespace"); AssertEquals("Remove (3)", "http://www.w3.org/XML/1998/namespace", ns.LookupNamespace("xml")); ns.RemoveNamespace ("xmlns", "http://www.w3.org/2000/xmlns/"); AssertEquals("Remove (3)", "http://www.w3.org/2000/xmlns/", ns.LookupNamespace("xmlns")); // Add and remove a particular namespace. ns.AddNamespace("foo", "uri"); ns.RemoveNamespace("foo", "uri"); AssertNull("Remove (4)", ns.LookupNamespace("foo")); // Make sure that we cannot remove namespaces in parent scopes. ns.AddNamespace("foo", "uri"); ns.PushScope(); ns.RemoveNamespace("foo", "uri"); AssertEquals("Remove (5)", "uri", ns.LookupNamespace("foo")); // Try removing a namespace with the wrong URI or prefix. ns.AddNamespace("foo", "uri2"); ns.RemoveNamespace("foo", "uri"); AssertEquals("Remove (6)", "uri2", ns.LookupNamespace("foo")); ns.RemoveNamespace("foo2", "uri"); AssertEquals("Remove (7)", "uri2", ns.LookupNamespace("foo")); }
public static string ParsificazioneXmlViaggi(string xmlResponse, UserProfile user, int step, int proposalCode, bool cancellaNodoMessaggiErrore = false) { string xml = string.Empty; XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlResponse); if (doc.FirstChild.NodeType == XmlNodeType.XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } #region Namespace xml XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); if (doc.DocumentElement.Attributes["xmlns:S"] != null) { string s = doc.DocumentElement.Attributes["xmlns:S"].Value; nsmgr.AddNamespace("S", s); } XmlNode nodeRoot = doc.SelectSingleNode("S:Envelope/S:Body", nsmgr); if (nodeRoot != null) { XmlNode nodeNamespace = nodeRoot.LastChild; if (nodeNamespace.Attributes["xmlns:ns3"] != null) { string ns3 = nodeNamespace.Attributes["xmlns:ns3"].Value; nsmgr.AddNamespace("ns3", ns3); } if (nodeNamespace.Attributes["xmlns:ns2"] != null) { string ns2 = nodeNamespace.Attributes["xmlns:ns2"].Value; nsmgr.AddNamespace("ns2", ns2); } if (nodeNamespace.Attributes["xmlns:ns7"] != null) { string ns7 = nodeNamespace.Attributes["xmlns:ns7"].Value; nsmgr.AddNamespace("ns7", ns7); } if (nodeNamespace.Attributes["xmlns:ns9"] != null) { string ns9 = nodeNamespace.Attributes["xmlns:ns9"].Value; nsmgr.AddNamespace("ns9", ns9); } } #endregion // nodo quote principale XmlNode nodoQuote = null; XmlNodeList listaNodiFattori = null; XmlNodeList ListaNodiSezioni = null; #region Inietto il numero di preventivo (appena staccato chiamando il SaveSHPQuote oppure re-iniettato ogni volta) e rimuovo eventuali nodi errore string stringaQuote = "S:Envelope/S:Body/{0}:{1}/return/{0}:quote"; XmlNodeList nodoQuoteList = doc.SelectNodes(string.Format(stringaQuote, "ns3", "getSHPQuoteResponse"), nsmgr); if (nodoQuoteList != null & nodoQuoteList.Count <= 0) { nodoQuoteList = doc.SelectNodes(string.Format(stringaQuote, "ns3", "pricingSHPQuoteResponse"), nsmgr); } if (nodoQuoteList != null & nodoQuoteList.Count <= 0) { nodoQuoteList = doc.SelectNodes(string.Format(stringaQuote, "ns2", "getSHPQuoteResponse"), nsmgr); } if (nodoQuoteList != null & nodoQuoteList.Count <= 0) { nodoQuoteList = doc.SelectNodes(string.Format(stringaQuote, "ns2", "pricingSHPQuoteResponse"), nsmgr); } if (nodoQuoteList != null & nodoQuoteList.Count > 0) { nodoQuote = nodoQuoteList[0]; if (cancellaNodoMessaggiErrore) { // RIMUOVO IL PRECEDENTE ERRORE SE C'E' STATO XmlNode nodoErrore = nodoQuote.SelectSingleNode("ns7:messages", nsmgr); if (nodoErrore != null) { nodoErrore.RemoveAll(); } } } #endregion if (step == 2) { #region Iniettando la data di policyExpirationDate // Chat con Mirko del 24 settembre 2018 /* * di default è impostata a 2 giorni della data effetto * es: data effetto 24/09/2018 data scadenza: 26/09/2018 * * per il viaggi mettere la data di fine viaggio */ XmlNode nodoPolicyExpirationDate = nodoQuote.SelectSingleNode("ns7:policyExpirationDate", nsmgr); XmlNode nodoDataPol = null; if (nodoPolicyExpirationDate != null) { // nodoDataPol = nodoPolicyExpirationDate.SelectSingleNode("ns2:data", nsmgr); nodoDataPol = nodoPolicyExpirationDate.ChildNodes[0]; string dataPolicy = string.Format("{0}-{1}-{2}T00:00:00+0{3}:00", user.DataFine.Split('/')[2], (user.DataFine.Split('/')[1].Length == 1) ? "0" + user.DataFine.Split('/')[1] : user.DataFine.Split('/')[1], user.DataFine.Split('/')[0], TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalHours.ToString()); if (nodoDataPol != null) { nodoDataPol.InnerText = dataPolicy; } else { nodoDataPol = doc.CreateElement("ns2:data", nsmgr.LookupNamespace("ns2")); nodoDataPol.InnerText = dataPolicy; nodoPolicyExpirationDate.AppendChild(nodoDataPol); } } #endregion #region Iniettando nodo requesterEMailAddress per gestione tracking preventivi Casa/Viaggi (IM9950680 RGI). Mail del 02/01/2019 ore 11:07 da Mirko Rizzo XmlNode nodoRequesterEmail = nodoQuote.SelectSingleNode("ns7:requesterEMailAddress", nsmgr); if (nodoRequesterEmail == null) { nodoRequesterEmail = doc.CreateElement("ns7:requesterEMailAddress", nsmgr.LookupNamespace("ns7")); nodoRequesterEmail.InnerText = user.Email; nodoQuote.AppendChild(nodoRequesterEmail); } else { nodoRequesterEmail.InnerText = user.Email; } #endregion #region parsificazione xml con i valori scelti dall'utente listaNodiFattori = nodoQuote.SelectNodes("ns7:product/ns9:assets/ns9:instances/ns9:factors", nsmgr); ListaNodiSezioni = nodoQuote.SelectNodes("ns7:product/ns9:assets/ns9:instances/ns9:sections", nsmgr); if (listaNodiFattori != null & listaNodiFattori.Count > 0) { string codiceFattore = string.Empty; XmlNode nodoValue; XmlNode nodoManuallySet; XmlNode nodoBooleanManuallySet; foreach (XmlNode nodoChildFactor in listaNodiFattori) { // per ogni elemento attivo del form Step1 bisogna verificare l'associazione con il codice che si sta esaminando dell'xml e nel nodo "value" settare il valore corrispondente codiceFattore = nodoChildFactor.SelectSingleNode("ns9:code", nsmgr).InnerText; // non faccio nulla per i due fattori di Pacchetto if (codiceFattore == "2PACC3" || codiceFattore == "2PACC4") { continue; } nodoValue = nodoChildFactor.SelectSingleNode("ns9:value", nsmgr); nodoManuallySet = nodoChildFactor.SelectSingleNode("ns9:manuallySet", nsmgr); if (nodoManuallySet != null) { // nodoBooleanManuallySet = nodoManuallySet.SelectSingleNode("ns2:boolean", nsmgr); nodoBooleanManuallySet = nodoManuallySet.ChildNodes[0]; if (nodoBooleanManuallySet == null) { nodoBooleanManuallySet = nodoManuallySet.SelectSingleNode("ns3:boolean", nsmgr); } if (nodoBooleanManuallySet != null) { nodoBooleanManuallySet.InnerText = "true"; } } switch (codiceFattore) { case "2LICOP": // Fattore Concept di prodotto (Proposta) if (nodoValue != null) { nodoValue.InnerText = Convert.ToString(proposalCode); } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = Convert.ToString(proposalCode); nodoChildFactor.AppendChild(nodoValue); } break; case "3ESTER": // Destinazione (estensione territoriale) if (nodoValue != null) { nodoValue.InnerText = user.Dest; } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.Dest; nodoChildFactor.AppendChild(nodoValue); } break; case "1DEFCV": // Data inizio viaggio (data effetto copertura viaggio) if (nodoValue != null) { nodoValue.InnerText = GetDataRGI(user.DataInizio); // RGI vuole es: 2018/05/29, io ho 29/05/2018 } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = GetDataRGI(user.DataInizio); // RGI vuole es: 2018/05/29, io ho 29/05/2018 nodoChildFactor.AppendChild(nodoValue); } break; case "1DSCCO": // Data fine viaggio (data scadenza copertura viaggio) if (nodoValue != null) { nodoValue.InnerText = GetDataRGI(user.DataFine); // RGI vuole es: 2018/05/29, io ho 29/05/2018 } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = GetDataRGI(user.DataFine); // RGI vuole es: 2018/05/29, io ho 29/05/2018 nodoChildFactor.AppendChild(nodoValue); } break; case "1NUPER": // Numero persone if (nodoValue != null) { nodoValue.InnerText = user.NumPartecipanti.ToString(); } else { nodoValue = doc.CreateElement("ns9:value", nsmgr.LookupNamespace("ns9")); nodoValue.InnerText = user.NumPartecipanti.ToString(); nodoChildFactor.AppendChild(nodoValue); } break; } } // NB => il doc.Innerxml ha già le variazioni } #endregion } xml = doc.InnerXml; return(xml); }
private void Load(string Filename, XmlDocument Document, XmlNamespaceManager NSMgr) { Log("Message", "Load", String.Format("Filename : {0}", Filename)); IsFileImportLoadingRunning = true; //Store the filename we're using this.Filename = Filename; //Create an XML document object from the file specified Document.Load(Filename); //Find the Header node XmlNode headerNode = Document.SelectSingleNode("/ia:Message/ia:Header", NSMgr); if (headerNode == null) { headerNode = Document.CreateElement("Header", NSMgr.LookupNamespace("ia")); if (Document.DocumentElement.HasChildNodes) { Document.DocumentElement.InsertBefore(headerNode, Document.DocumentElement.FirstChild); } else { Document.DocumentElement.AppendChild(headerNode); } } this.Header = new ILR.Header(headerNode, NSMgr); //Find the LearningProvider node XmlNode learningProviderNode = Document.SelectSingleNode("/ia:Message/ia:LearningProvider", NSMgr); //Find the Learner nodes XmlNodeList learnerNodes = Document.SelectNodes("/ia:Message/ia:Learner", NSMgr); //If we have no LearningProvider node create one in the correct place if (learningProviderNode == null) { learningProviderNode = Document.CreateElement("LearningProvider", NSMgr.LookupNamespace("ia")); if (learnerNodes.Count == 0) { Document.DocumentElement.AppendChild(learningProviderNode); } else { Document.DocumentElement.InsertBefore(learningProviderNode, learnerNodes.Item(0)); } } //Create a LearningProvider instance this.LearningProvider = new ILR.LearningProvider(learningProviderNode, NSMgr); //Create Learner instances for all of the learners in the XML foreach (XmlNode node in learnerNodes) { Learner newInstance = new Learner(node, NSMgr, IsFileImportLoadingRunning); newInstance.Message = this; newInstance.ResequenceAimSeqNumber(); newInstance.IsFileImportLoadingRunning = false; LearnerList.Add(newInstance); Log("Message", "Load", String.Format("Add Leaerner {0} of {1} - {2}", LearnerList.Count, learnerNodes.Count, newInstance.LearnRefNumber)); } //Find the LearnerDestinationandProgression nodes XmlNodeList learnerDestinationandProgressionNodes = Document.SelectNodes("/ia:Message/ia:LearnerDestinationandProgression", NSMgr); //Create LearnerDestinationandProgression instances for all of the LearnerDestinationandProgressions in the XML foreach (XmlNode node in learnerDestinationandProgressionNodes) { LearnerDestinationandProgression newLDP = new LearnerDestinationandProgression(node, NSMgr); newLDP.Message = this; LearnerDestinationandProgressionList.Add(newLDP); Log("Message", "Load", String.Format("Add LDP {0} of {1} - {2}", LearnerDestinationandProgressionList.Count, learnerDestinationandProgressionNodes.Count, newLDP.LearnRefNumber)); } //foreach (Learner l in LearnerList) //{ // foreach (LearningDelivery ld in l.LearningDeliveryList) // { // ld.IsImportRunning = false; // } // l.IsFileImportLoadingRunning = false; //} IsFileImportLoadingRunning = false; }
/// <summary> /// Checks output state and flushes pending attributes and namespaces /// when it's appropriate. /// </summary> private void CheckState() { if (_state == WriteState.Element) { //Emit pending attributes _nsManager.PushScope(); foreach (string prefix in _currentNamespaceDecls.Keys) { string uri = _currentNamespaceDecls [prefix] as string; if (_nsManager.LookupNamespace(prefix, false) == uri) { continue; } newNamespaces.Add(prefix); _nsManager.AddNamespace(prefix, uri); } for (int i = 0; i < pendingAttributesPos; i++) { Attribute attr = pendingAttributes [i]; string prefix = attr.Prefix; if (prefix == XmlNamespaceManager.PrefixXml && attr.Namespace != XmlNamespaceManager.XmlnsXml) { // don't allow mapping from "xml" to other namespaces. prefix = String.Empty; } string existing = _nsManager.LookupPrefix(attr.Namespace, false); if (prefix.Length == 0 && attr.Namespace.Length > 0) { prefix = existing; } if (attr.Namespace.Length > 0) { if (prefix == null || prefix == String.Empty) { // empty prefix is not allowed // for non-local attributes. prefix = "xp_" + _xpCount++; } if (existing != prefix) { while (_nsManager.LookupNamespace(prefix) != null) { prefix = "xp_" + _xpCount++; } newNamespaces.Add(prefix); _currentNamespaceDecls.Add(prefix, attr.Namespace); _nsManager.AddNamespace(prefix, attr.Namespace); } } Emitter.WriteAttributeString(prefix, attr.LocalName, attr.Namespace, attr.Value); } for (int i = 0; i < newNamespaces.Count; i++) { string prefix = (string)newNamespaces [i]; string uri = _currentNamespaceDecls [prefix] as string; if (prefix != String.Empty) { Emitter.WriteAttributeString("xmlns", prefix, XmlNamespaceManager.XmlnsXmlns, uri); } else { Emitter.WriteAttributeString(String.Empty, "xmlns", XmlNamespaceManager.XmlnsXmlns, uri); } } _currentNamespaceDecls.Clear(); //Attributes flushed, state is Content now _state = WriteState.Content; newNamespaces.Clear(); } _canProcessAttributes = false; }
/// <summary> /// This is used to modify the GenerateRefInfo.proj file for use with Script# /// </summary> private void ModifyGenerateRefInfoProject() { XmlNamespaceManager nsm; XmlDocument project; XmlNode target, task; XmlAttribute attr; string projectFile; projectFile = builder.WorkingFolder + "GenerateRefInfo.proj"; // If the project doesn't exist we have nothing to do. However, it could be that some other plug-in // has bypassed it so only issue a warning. if (!File.Exists(projectFile)) { builder.ReportWarning("SSP0003", "The reflection information generation project '{0}' could " + "not be found. The Script# plug-in did not run successfully.", projectFile); return; } builder.ReportProgress("Adding Script# AfterGenerateRefInfo tasks to GenerateRefInfo.proj"); // Add the transform that fixes up the Script# elements to the AfterGenerateRefInfo project target. // Note that we use a customized version that adds a <scriptSharp /> element to each API node so that // our custom JavaScript syntax generator applies the casing rules to the member names. project = new XmlDocument(); project.Load(projectFile); nsm = new XmlNamespaceManager(project.NameTable); nsm.AddNamespace("MSBuild", project.DocumentElement.NamespaceURI); target = project.SelectSingleNode("//MSBuild:Target[@Name='AfterGenerateRefInfo']", nsm); if (target == null) { throw new BuilderException("SSP0004", "Unable to locate AfterGenerateRefInfo target " + "in project file"); } task = project.CreateElement("Message", nsm.LookupNamespace("MSBuild")); attr = project.CreateAttribute("Text"); attr.Value = "Fixing up Script# elements..."; task.Attributes.Append(attr); target.AppendChild(task); task = project.CreateElement("Copy", nsm.LookupNamespace("MSBuild")); attr = project.CreateAttribute("SourceFiles"); attr.Value = "reflection.org"; task.Attributes.Append(attr); attr = project.CreateAttribute("DestinationFiles"); attr.Value = "scriptsharp.org"; task.Attributes.Append(attr); target.AppendChild(task); task = project.CreateElement("Microsoft.Ddue.Tools.MSBuild.XslTransform", nsm.LookupNamespace("MSBuild")); attr = project.CreateAttribute("WorkingFolder"); attr.Value = "$(WorkingFolder)"; task.Attributes.Append(attr); attr = project.CreateAttribute("Transformations"); attr.Value = Path.Combine(ComponentUtilities.ToolsFolder, @"~\ProductionTransforms\FixScriptSharp.xsl"); task.Attributes.Append(attr); attr = project.CreateAttribute("InputFile"); attr.Value = "scriptsharp.org"; task.Attributes.Append(attr); attr = project.CreateAttribute("OutputFile"); attr.Value = "reflection.org"; task.Attributes.Append(attr); target.AppendChild(task); project.Save(projectFile); }
/// <summary> /// Determine whether an ElementCtor, AttributeCtor, or NamespaceDecl's namespace is already declared. If it is, /// set the IsNamespaceInScope property to True. Otherwise, add the namespace to the set of in-scope namespaces if /// addInScopeNmsp is True. Return false if the name is computed or is invalid. /// </summary> private bool CheckNamespaceInScope(QilBinary nd) { QilName ndName; string prefix, ns, prefixExisting, nsExisting; XPathNodeType nodeType; switch (nd.NodeType) { case QilNodeType.ElementCtor: case QilNodeType.AttributeCtor: ndName = nd.Left as QilName; if (ndName != null) { prefix = ndName.Prefix; ns = ndName.NamespaceUri; nodeType = (nd.NodeType == QilNodeType.ElementCtor) ? XPathNodeType.Element : XPathNodeType.Attribute; break; } // Not a literal name, so return false return(false); default: Debug.Assert(nd.NodeType == QilNodeType.NamespaceDecl); prefix = (string)(QilLiteral)nd.Left; ns = (string)(QilLiteral)nd.Right; nodeType = XPathNodeType.Namespace; break; } // Attribute with null namespace and xmlns:xml are always in-scope if (nd.NodeType == QilNodeType.AttributeCtor && ns.Length == 0 || prefix == "xml" && ns == XmlReservedNs.NsXml) { XmlILConstructInfo.Write(nd).IsNamespaceInScope = true; return(true); } // Don't process names that are invalid if (!ValidateNames.ValidateName(prefix, string.Empty, ns, nodeType, ValidateNames.Flags.CheckPrefixMapping)) { return(false); } // Atomize names prefix = _nsmgr.NameTable.Add(prefix); ns = _nsmgr.NameTable.Add(ns); // Determine whether namespace is already in-scope for (int iNmsp = 0; iNmsp < _cntNmsp; iNmsp++) { _nsmgr.GetNamespaceDeclaration(iNmsp, out prefixExisting, out nsExisting); // If prefix is already declared, if ((object)prefix == (object)prefixExisting) { // Then if the namespace is the same, this namespace is redundant if ((object)ns == (object)nsExisting) { XmlILConstructInfo.Write(nd).IsNamespaceInScope = true; } // Else quit searching, because any further matching prefixes will be hidden (not in-scope) Debug.Assert(nd.NodeType != QilNodeType.NamespaceDecl || !_nsmgr.HasNamespace(prefix) || _nsmgr.LookupNamespace(prefix) == ns, "Compilers must ensure that namespace declarations do not conflict with the namespace used by the element constructor."); break; } } // If not in-scope, then add if it's allowed if (_addInScopeNmsp) { _nsmgr.AddNamespace(prefix, ns); _cntNmsp++; } return(true); }
private static void AddAttribute( JsonReader reader, IXmlDocument document, IXmlNode currentNode, string attributeName, XmlNamespaceManager manager, string attributePrefix) { string str1 = XmlConvert.EncodeName(attributeName); string str2 = reader.Value.ToString(); IXmlNode attribute = !string.IsNullOrEmpty(attributePrefix) ? document.CreateAttribute(str1, manager.LookupNamespace(attributePrefix), str2) : document.CreateAttribute(str1, str2); ((IXmlElement)currentNode).SetAttributeNode(attribute); }
private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager) { string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); IXmlElement element = (!string.IsNullOrEmpty(ns)) ? document.CreateElement(elementName, ns) : document.CreateElement(elementName); return(element); }
private IXmlElement CreateElement( string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager) { string str = XmlConvert.EncodeName(elementName); string namespaceUri = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); return(string.IsNullOrEmpty(namespaceUri) ? document.CreateElement(str) : document.CreateElement(str, namespaceUri)); }
public override string LookupNamespace(string prefix) { return(nsmgr.LookupNamespace(prefix)); }
public static void AddStyleToXml(XmlDocument xml, XmlNode head, XmlNamespaceManager nsmgr, string name, string fontFamily, string fontWeight, string fontStyle, string color, string fontSize) { var styleNode = xml.CreateNode(XmlNodeType.Element, string.Empty, "style", nsmgr.LookupNamespace("ttml")); XmlAttribute attr = xml.CreateAttribute("xml:id", "http://www.w3.org/ns/10/ttml#style"); attr.InnerText = name; styleNode.Attributes.Append(attr); attr = xml.CreateAttribute("tts:fontFamily", "http://www.w3.org/ns/10/ttml#style"); attr.InnerText = fontFamily; styleNode.Attributes.Append(attr); attr = xml.CreateAttribute("tts:fontWeight", "http://www.w3.org/ns/10/ttml#style"); attr.InnerText = fontWeight; styleNode.Attributes.Append(attr); attr = xml.CreateAttribute("tts:fontStyle", "http://www.w3.org/ns/10/ttml#style"); attr.InnerText = fontStyle; styleNode.Attributes.Append(attr); attr = xml.CreateAttribute("tts:color", "http://www.w3.org/ns/10/ttml#style"); attr.InnerText = color; styleNode.Attributes.Append(attr); attr = xml.CreateAttribute("tts:fontSize", "http://www.w3.org/ns/10/ttml#style"); attr.InnerText = fontSize; styleNode.Attributes.Append(attr); foreach (XmlNode innerNode in head.ChildNodes) { if (innerNode.Name == "styling") { innerNode.AppendChild(styleNode); break; } } }
private XmlElement LoadElementNode(bool root) { Debug.Assert(_reader.NodeType == XmlNodeType.Element); XmlReader r = _reader; bool fEmptyElement = r.IsEmptyElement; XmlElement element = _dummyDocument.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI); element.IsEmpty = fEmptyElement; if (root) { _parentNode = element; } else { XmlAttributeCollection attributes = element.Attributes; if (r.MoveToFirstAttribute()) { do { if (Ref.Equal(r.NamespaceURI, _schemaNames.NsXmlNs)) { //Namespace Attribute _annotationNSManager.AddNamespace(r.Prefix.Length == 0 ? string.Empty : _reader.LocalName, _reader.Value); } XmlAttribute attr = LoadAttributeNode(); attributes.Append(attr); } while (r.MoveToNextAttribute()); } r.MoveToElement(); string ns = _annotationNSManager.LookupNamespace(r.Prefix); if (ns == null) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager.LookupNamespace(r.Prefix)); attributes.Append(attr); } else if (ns.Length == 0) { //string.Empty prefix is mapped to string.Empty NS by default string elemNS = _namespaceManager.LookupNamespace(r.Prefix); if (elemNS != string.Empty) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, elemNS); attributes.Append(attr); } } while (r.MoveToNextAttribute()) { if (r.Prefix.Length != 0) { string attNS = _annotationNSManager.LookupNamespace(r.Prefix); if (attNS == null) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager.LookupNamespace(r.Prefix)); attributes.Append(attr); } } } r.MoveToElement(); _parentNode.AppendChild(element); if (!r.IsEmptyElement) { _parentNode = element; } } return(element); }
private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager) { return((!string.IsNullOrEmpty(elementPrefix)) ? document.CreateElement(elementName, manager.LookupNamespace(elementPrefix)) : document.CreateElement(elementName)); }
private void buttonOK_Click(object sender, EventArgs e) { XmlNode node = _xml.DocumentElement.SelectSingleNode("ttml:head/ttml:metadata/ttml:title", _nsmgr); if (node != null) { if (string.IsNullOrWhiteSpace(textBoxTitle.Text) && string.IsNullOrWhiteSpace(textBoxDescription.Text)) { _xml.DocumentElement.SelectSingleNode("ttml:head", _nsmgr).RemoveChild(_xml.DocumentElement.SelectSingleNode("ttml:head/ttml:metadata", _nsmgr)); } else { node.InnerText = textBoxTitle.Text; } } else if (!string.IsNullOrWhiteSpace(textBoxTitle.Text)) { var head = _xml.DocumentElement.SelectSingleNode("ttml:head", _nsmgr); if (head == null) { head = _xml.CreateElement("ttml", "head", _nsmgr.LookupNamespace("ttml")); _xml.DocumentElement.PrependChild(head); } var metadata = _xml.DocumentElement.SelectSingleNode("ttml:head/ttml:metadata", _nsmgr); if (metadata == null) { metadata = _xml.CreateElement("ttml", "metadata", _nsmgr.LookupNamespace("ttml")); head.PrependChild(metadata); } var title = _xml.CreateElement("ttml", "title", _nsmgr.LookupNamespace("ttml")); metadata.InnerText = textBoxTitle.Text; metadata.AppendChild(title); } node = _xml.DocumentElement.SelectSingleNode("ttml:head/ttml:metadata/ttml:desc", _nsmgr); if (node != null) { node.InnerText = textBoxDescription.Text; } else if (!string.IsNullOrWhiteSpace(textBoxDescription.Text)) { var head = _xml.DocumentElement.SelectSingleNode("ttml:head", _nsmgr); if (head == null) { head = _xml.CreateElement("ttml", "head", _nsmgr.LookupNamespace("ttml")); _xml.DocumentElement.PrependChild(head); } var metadata = _xml.DocumentElement.SelectSingleNode("ttml:head/ttml:metadata", _nsmgr); if (metadata == null) { metadata = _xml.CreateElement("ttml", "metadata", _nsmgr.LookupNamespace("ttml")); head.PrependChild(metadata); } var desc = _xml.CreateElement("ttml", "desc", _nsmgr.LookupNamespace("ttml")); desc.InnerText = textBoxDescription.Text; metadata.AppendChild(desc); } XmlAttribute attr = _xml.DocumentElement.Attributes["xml:lang"]; if (attr != null) { attr.Value = comboBoxLanguage.Text; if (attr.Value.Length == 0) { _xml.DocumentElement.Attributes.Remove(attr); } } else if (comboBoxLanguage.Text.Length > 0) { attr = _xml.CreateAttribute("xml", "lang", _nsmgr.LookupNamespace("xml")); attr.Value = comboBoxLanguage.Text; _xml.DocumentElement.Attributes.Prepend(attr); } attr = _xml.DocumentElement.Attributes["ttp:timeBase"]; if (attr != null) { attr.InnerText = comboBoxTimeBase.Text; if (attr.Value.Length == 0) { _xml.DocumentElement.Attributes.Remove(attr); } } else if (comboBoxTimeBase.Text.Length > 0) { attr = _xml.CreateAttribute("ttp", "timeBase", _nsmgr.LookupNamespace("ttp")); attr.Value = comboBoxTimeBase.Text; _xml.DocumentElement.Attributes.Append(attr); } attr = _xml.DocumentElement.Attributes["ttp:frameRate"]; if (attr != null) { attr.InnerText = comboBoxFrameRate.Text; if (attr.Value.Length == 0) { _xml.DocumentElement.Attributes.Remove(attr); } } else if (comboBoxFrameRate.Text.Length > 0) { attr = _xml.CreateAttribute("ttp", "frameRate", _nsmgr.LookupNamespace("ttp")); attr.Value = comboBoxFrameRate.Text; _xml.DocumentElement.Attributes.Append(attr); } attr = _xml.DocumentElement.Attributes["ttp:frameRateMultiplier"]; if (attr != null) { attr.InnerText = comboBoxFrameRateMultiplier.Text; if (attr.Value.Length == 0) { _xml.DocumentElement.Attributes.Remove(attr); } } else if (comboBoxFrameRateMultiplier.Text.Length > 0) { attr = _xml.CreateAttribute("ttp", "frameRateMultiplier", _nsmgr.LookupNamespace("ttp")); attr.Value = comboBoxFrameRateMultiplier.Text; _xml.DocumentElement.Attributes.Append(attr); } attr = _xml.DocumentElement.Attributes["ttp:dropMode"]; if (attr != null) { attr.InnerText = comboBoxDropMode.Text; if (attr.Value.Length == 0) { _xml.DocumentElement.Attributes.Remove(attr); } } else if (comboBoxDropMode.Text.Length > 0) { attr = _xml.CreateAttribute("ttp", "dropMode", _nsmgr.LookupNamespace("ttp")); attr.Value = comboBoxDropMode.Text; _xml.DocumentElement.Attributes.Append(attr); } node = _xml.DocumentElement.SelectSingleNode("ttml:body", _nsmgr); if (node != null && node.Attributes["style"] != null) { node.Attributes["style"].Value = comboBoxDefaultStyle.Text; } else if (comboBoxDefaultStyle.Text.Length > 0 && node != null) { attr = _xml.CreateAttribute("style"); attr.Value = comboBoxDefaultStyle.Text; node.Attributes.Append(attr); } node = _xml.DocumentElement.SelectSingleNode("ttml:body", _nsmgr); if (node != null && node.Attributes["region"] != null) { node.Attributes["region"].Value = comboBoxDefaultRegion.Text; } else if (comboBoxDefaultRegion.Text.Length > 0 && node != null) { attr = _xml.CreateAttribute("region"); attr.Value = comboBoxDefaultRegion.Text; node.Attributes.Append(attr); } _subtitle.Header = _xml.OuterXml; Configuration.Settings.SubtitleSettings.TimedText10TimeCodeFormat = comboBoxTimeCodeFormat.SelectedItem.ToString(); Configuration.Settings.SubtitleSettings.TimedText10FileExtension = comboBoxFileExtensions.SelectedItem.ToString(); DialogResult = DialogResult.OK; }
private Dictionary <string, string> ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager) { Dictionary <string, string> attributeNameValues = new Dictionary <string, string>(); bool finishedAttributes = false; bool finishedElement = false; // 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(); string attributeValue; if (!string.IsNullOrEmpty(attributeName)) { char firstChar = attributeName[0]; switch (firstChar) { case '@': attributeName = attributeName.Substring(1); reader.Read(); attributeValue = reader.Value.ToString(); attributeNameValues.Add(attributeName, attributeValue); string namespacePrefix; if (IsNamespaceAttribute(attributeName, out namespacePrefix)) { manager.AddNamespace(namespacePrefix, attributeValue); } break; case '$': attributeName = attributeName.Substring(1); reader.Read(); attributeValue = reader.Value.ToString(); // check that JsonNamespaceUri is in scope // if it isn't then add it to document and namespace manager string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri); if (jsonPrefix == null) { // ensure that the prefix used is free int?i = null; while (manager.LookupNamespace("json" + i) != null) { i = i.GetValueOrDefault() + 1; } jsonPrefix = "json" + i; attributeNameValues.Add("xmlns:" + jsonPrefix, JsonNamespaceUri); manager.AddNamespace(jsonPrefix, JsonNamespaceUri); } attributeNameValues.Add(jsonPrefix + ":" + attributeName, attributeValue); break; default: finishedAttributes = true; break; } } else { finishedAttributes = true; } break; case JsonToken.EndObject: finishedElement = true; break; default: throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType); } } } return(attributeNameValues); }
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 (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) { // 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.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; } }
// Check that a namespace manager's enumerator returns what we expect. private static void CheckEnum(XmlNamespaceManager ns, String fooValue) { int count = 0; foreach(String name in ns) { ++count; if(name == "xml") { AssertEquals ("Enum (1)", "http://www.w3.org/XML/1998/namespace", ns.LookupNamespace(name)); } else if(name == "xmlns") { AssertEquals ("Enum (2)", "http://www.w3.org/2000/xmlns/", ns.LookupNamespace(name)); } else if(name == "foo") { AssertEquals ("Enum (3)", fooValue, ns.LookupNamespace(name)); } else if(name == "") { AssertEquals ("Enum (4)", "", ns.LookupNamespace(name)); } } AssertEquals("Enum (5)", 4, count); }
private void CopyVmlDrawing(ExcelWorksheet origSheet, ExcelWorksheet newSheet) { var xml = origSheet.VmlDrawingsComments.VmlDrawingXml.OuterXml; var vmlUri = new Uri(string.Format("/xl/drawings/vmlDrawing{0}.vml", newSheet.SheetID), UriKind.Relative); var part = _pck.Package.CreatePart(vmlUri, "application/vnd.openxmlformats-officedocument.vmlDrawing", _pck.Compression); using (var streamDrawing = new StreamWriter(part.GetStream(FileMode.Create, FileAccess.Write))) { streamDrawing.Write(xml); } //Add the relationship ID to the worksheet xml. PackageRelationship vmlRelation = newSheet.Part.CreateRelationship(PackUriHelper.GetRelativeUri(newSheet.WorksheetUri, vmlUri), TargetMode.Internal, ExcelPackage.schemaRelationships + "/vmlDrawing"); var e = newSheet.WorksheetXml.SelectSingleNode("//d:legacyDrawing", _namespaceManager) as XmlElement; if (e == null) { e = newSheet.WorksheetXml.CreateNode(XmlNodeType.Entity, "//d:legacyDrawing", _namespaceManager.LookupNamespace("d")) as XmlElement; } if (e != null) { e.SetAttribute("id", ExcelPackage.schemaRelationships, vmlRelation.Id); } }
private void AddSchemaType(XmlDictionaryWriter writer, TypeToBuild toBuild, string name, bool isArray = false, string @namespace = null, bool isAttribute = false, bool isListWithoutWrapper = false) { var type = toBuild.Type; var typeInfo = type.GetTypeInfo(); if (typeInfo.IsByRef) { type = typeInfo.GetElementType(); } var typeName = type.GetSerializedTypeName(); if (writer.TryAddSchemaTypeFromXmlSchemaProviderAttribute(type, name, SoapSerializer.XmlSerializer, _xmlNamespaceManager)) { return; } var underlyingType = Nullable.GetUnderlyingType(type); //if type is a nullable non-system struct if (underlyingType?.IsValueType == true && !underlyingType.IsEnum && underlyingType.Namespace != null && underlyingType.Namespace != "System" && !underlyingType.Namespace.StartsWith("System.")) { AddSchemaType(writer, new TypeToBuild(underlyingType) { ChildElementName = toBuild.TypeName }, name, isArray, @namespace, isAttribute); return; } writer.WriteStartElement(isAttribute ? "attribute" : "element", Namespaces.XMLNS_XSD); // Check for null, since we may use empty NS if (@namespace != null) { writer.WriteAttributeString("targetNamespace", @namespace); } else if (typeInfo.IsEnum || underlyingType?.IsEnum == true || (typeInfo.IsValueType && typeInfo.Namespace != null && (typeInfo.Namespace == "System" || typeInfo.Namespace.StartsWith("System."))) || (type.Name == "String") || (type.Name == "Byte[]")) { XmlQualifiedName xsTypename; if (typeof(DateTimeOffset).IsAssignableFrom(type)) { if (string.IsNullOrEmpty(name)) { name = typeName; } Namespaces.AddNamespaceIfNotAlreadyPresentAndGetPrefix(_xmlNamespaceManager, "nsdto", Namespaces.SYSTEM_NS); xsTypename = new XmlQualifiedName(typeName, Namespaces.SYSTEM_NS); _buildDateTimeOffset = true; } else if (typeInfo.IsEnum) { xsTypename = new XmlQualifiedName(typeName, _xmlNamespaceManager.LookupNamespace("tns")); _enumToBuild.Enqueue(type); } else if (underlyingType?.IsEnum == true) { xsTypename = new XmlQualifiedName(underlyingType.GetSerializedTypeName(), _xmlNamespaceManager.LookupNamespace("tns")); _enumToBuild.Enqueue(underlyingType); } else { if (underlyingType != null) { xsTypename = ResolveType(underlyingType); writer.WriteAttributeString("nillable", "true"); } else { xsTypename = ResolveType(type); } } if (isAttribute) { // skip occurence } else if (isArray) { writer.WriteAttributeString("minOccurs", "0"); writer.WriteAttributeString("maxOccurs", "unbounded"); writer.WriteAttributeString("nillable", "true"); } else { writer.WriteAttributeString("minOccurs", type.IsValueType ? "1" : "0"); writer.WriteAttributeString("maxOccurs", "1"); } if (string.IsNullOrEmpty(name)) { name = xsTypename.Name; } writer.WriteAttributeString("name", name); writer.WriteAttributeString("type", $"{_xmlNamespaceManager.LookupPrefix(xsTypename.Namespace)}:{xsTypename.Name}"); } else { var newTypeToBuild = new TypeToBuild(type); if (!string.IsNullOrWhiteSpace(toBuild.ChildElementName)) { newTypeToBuild.ChildElementName = toBuild.ChildElementName; SetUniqueNameForDynamicType(newTypeToBuild); } writer.WriteAttributeString("minOccurs", "0"); if (isArray) { writer.WriteAttributeString("maxOccurs", "unbounded"); writer.WriteAttributeString("nillable", "true"); } else { writer.WriteAttributeString("maxOccurs", "1"); } if (type == typeof(Stream) || typeof(Stream).IsAssignableFrom(type)) { name = "StreamBody"; writer.WriteAttributeString("name", name); writer.WriteAttributeString("type", $"{_xmlNamespaceManager.LookupPrefix(Namespaces.XMLNS_XSD)}:base64Binary"); } else if (type.IsArray) { if (string.IsNullOrEmpty(name)) { name = typeName; } writer.WriteAttributeString("name", name); writer.WriteAttributeString("type", "tns:" + newTypeToBuild.TypeName); _complexTypeToBuild.Enqueue(newTypeToBuild); } else if (typeof(IEnumerable).IsAssignableFrom(type)) { if (type.GetGenericType().Name == "String") { if (string.IsNullOrEmpty(name)) { name = typeName; } var ns = $"q{_namespaceCounter++}"; writer.WriteXmlnsAttribute(ns, Namespaces.ARRAYS_NS); writer.WriteAttributeString("name", name); writer.WriteAttributeString("nillable", "true"); writer.WriteAttributeString("type", $"{ns}:{newTypeToBuild.TypeName}"); _arrayToBuild.Enqueue(type); } else { if (string.IsNullOrEmpty(name)) { name = typeName; } writer.WriteAttributeString("name", name); if (!isArray) { writer.WriteAttributeString("nillable", "true"); } if (isListWithoutWrapper) { newTypeToBuild = new TypeToBuild(newTypeToBuild.Type.GetGenericType()); } if (newTypeToBuild.IsAnonumous) { AddSchemaComplexType(writer, newTypeToBuild); } else { writer.WriteAttributeString("type", "tns:" + newTypeToBuild.TypeName); _complexTypeToBuild.Enqueue(newTypeToBuild); } } } else if (toBuild.IsAnonumous) { writer.WriteAttributeString("name", name); AddSchemaComplexType(writer, newTypeToBuild); } else { if (string.IsNullOrEmpty(name)) { name = typeName; } writer.WriteAttributeString("name", name); writer.WriteAttributeString("type", "tns:" + newTypeToBuild.TypeName); _complexTypeToBuild.Enqueue(newTypeToBuild); } } writer.WriteEndElement(); // element }
/* OPC Compliance methods */ /** * Check the element for the following OPC compliance rules: * <p> * Rule M4.2: A format consumer shall consider the use of the Markup * Compatibility namespace to be an error. * </p><p> * Rule M4.3: Producers shall not create a document element that contains * refinements to the Dublin Core elements, except for the two specified in * the schema: <dcterms:created> and <dcterms:modified> Consumers shall * consider a document element that violates this constraint to be an error. * </p><p> * Rule M4.4: Producers shall not create a document element that contains * the xml:lang attribute. Consumers shall consider a document element that * violates this constraint to be an error. * </p><p> * Rule M4.5: Producers shall not create a document element that contains * the xsi:type attribute, except for a <dcterms:created> or * <dcterms:modified> element where the xsi:type attribute shall be present * and shall hold the value dcterms:W3CDTF, where dcterms is the namespace * prefix of the Dublin Core namespace. Consumers shall consider a document * element that violates this constraint to be an error. * </p> */ public void CheckElementForOPCCompliance(XmlElement el) { foreach (XmlAttribute attr in el.Attributes) { if (attr.Name.StartsWith("xmlns:")) { string namespacePrefix = attr.Name.Substring(6); if (nsmgr.LookupNamespace(namespacePrefix).Equals(PackageNamespaces.MARKUP_COMPATIBILITY)) { // Rule M4.2 throw new InvalidFormatException( "OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error."); } } } // Check the current element // Rule M4.3 if (el.NamespaceURI.Equals( namespaceDcTerms) && !(el.LocalName.Equals(KEYWORD_CREATED) || el.LocalName .Equals(KEYWORD_MODIFIED))) { throw new InvalidFormatException( "OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error."); } // Rule M4.4 if (el.Attributes["lang", namespaceXML] != null) { throw new InvalidFormatException( "OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error."); } // Rule M4.5 if (el.NamespaceURI.Equals( namespaceDcTerms)) { // DCTerms namespace only use with 'created' and 'modified' elements String elName = el.LocalName; if (!(elName.Equals(KEYWORD_CREATED) || elName .Equals(KEYWORD_MODIFIED))) { throw new InvalidFormatException("Namespace error : " + elName + " shouldn't have the following naemspace -> " + namespaceDcTerms); } // Check for the 'xsi:type' attribute XmlAttribute typeAtt = el.Attributes["xsi:type"]; if (typeAtt == null) { throw new InvalidFormatException("The element '" + elName + "' must have the '" + nsmgr.LookupPrefix(namespaceXSI) + ":type' attribute present !"); } // Check for the attribute value => 'dcterms:W3CDTF' if (!typeAtt.Value.Equals(el.Prefix + ":W3CDTF")) { throw new InvalidFormatException("The element '" + elName + "' must have the '" + nsmgr.LookupPrefix(namespaceXSI) + ":type' attribute with the value '" + el.Prefix + ":W3CDTF', but had '" + typeAtt.Value + "' !"); } } // Check its children IEnumerator itChildren = el.GetEnumerator(); while (itChildren.MoveNext()) { if (itChildren.Current is XmlElement) { CheckElementForOPCCompliance((XmlElement)itChildren.Current); } } }
// depending on axis.Name & axis.Prefix, i will set the axis.URN; // also, record urn from prefix during this // 4 different types of element or attribute (with @ before it) combinations: // (1) a:b (2) b (3) * (4) a:* // i will check xpath to be strictly conformed from these forms // for (1) & (4) i will have URN set properly // for (2) the URN is null // for (3) the URN is empty private void SetURN(Axis axis, XmlNamespaceManager nsmgr) { if (axis.Prefix.Length != 0) { // (1) (4) axis.Urn = nsmgr.LookupNamespace(axis.Prefix); if (axis.Urn == null) { throw new XmlSchemaException(SR.Sch_UnresolvedPrefix, axis.Prefix); } } else if (axis.Name.Length != 0) { // (2) axis.Urn = null; } else { // (3) axis.Urn = ""; } }
internal static XmlQualifiedName Parse(string s, XmlNameTable nameTable, XmlNamespaceManager nsmgr, out string prefix) { int colonPos = s.IndexOf(':'); if (colonPos > 0) { char[] text = s.ToCharArray(); prefix = nameTable.Add(text, 0, colonPos); XmlConvert.VerifyNCName(prefix); s = nameTable.Add(text, colonPos + 1, text.Length - colonPos - 1); } else { prefix = string.Empty; s = nameTable.Add(s); } XmlConvert.VerifyNCName(s); string uri = nsmgr.LookupNamespace(prefix); if (uri == null) { throw new XmlException(Res.Xml_UnknownNs, prefix); } return new XmlQualifiedName(s, uri); }