LookupNamespace() public method

public LookupNamespace ( string prefix ) : string
prefix string
return string
示例#1
0
        // Public Methods
        #region CreateMasterContents(string styleFilePath, ArrayList odtFiles)
        public void CreateMasterContents(string styleFilePath, ArrayList odtFiles)
        {
            var doc = new XmlDocument();
            doc.Load(styleFilePath);
            var nsmgr = new XmlNamespaceManager(doc.NameTable);
            nsmgr.AddNamespace("office", "urn:oasis:names:tc:opendocument:xmlns:office:1.0");
            nsmgr.AddNamespace("text", "urn:oasis:names:tc:opendocument:xmlns:text:1.0");
            nsmgr.AddNamespace("xlink", "http://www.w3.org/1999/xlink");
          

            // if new stylename exists
            XmlElement root = doc.DocumentElement;
            string style = "//office:text";
            if (root != null)
            {

                XmlNode node = root.SelectSingleNode(style, nsmgr); // work
                if (node != null)
                {
                    for (int i = 0; i < odtFiles.Count; i++) // ODM - ODT 
                    {
                        string outputFile = odtFiles[i].ToString();
                        outputFile = Path.ChangeExtension(outputFile, "odt");
                        XmlNode newNode;
                        newNode = doc.CreateNode("element", "text:section", nsmgr.LookupNamespace("text"));
                        //attribute
                        XmlAttribute xmlAttrib = doc.CreateAttribute("text:style-name", nsmgr.LookupNamespace("text"));
                        xmlAttrib.Value = "SectODM";
                        newNode.Attributes.Append(xmlAttrib);

                        xmlAttrib = doc.CreateAttribute("text:name", nsmgr.LookupNamespace("text"));
                        xmlAttrib.Value = outputFile;
                        newNode.Attributes.Append(xmlAttrib);

                        xmlAttrib = doc.CreateAttribute("text:protected", nsmgr.LookupNamespace("text"));
                        xmlAttrib.Value = "false";
                        newNode.Attributes.Append(xmlAttrib);


                        XmlNode newNode1 = doc.CreateNode("element", "text:section-source", nsmgr.LookupNamespace("text"));
                        //attribute
                        XmlAttribute xmlAttrib1 = doc.CreateAttribute("xlink:href", nsmgr.LookupNamespace("xlink"));
                        xmlAttrib1.Value = "../" + outputFile;
                        newNode1.Attributes.Append(xmlAttrib1);


                        xmlAttrib1 = doc.CreateAttribute("text:filter-name", nsmgr.LookupNamespace("text"));
                        xmlAttrib1.Value = "writer8";
                        newNode1.Attributes.Append(xmlAttrib1);

                        newNode.AppendChild(newNode1);
                        node.AppendChild(newNode);
                    }
                }
            }

            doc.Save(styleFilePath);

        }
        /// <summary>
        /// Inserts Xml markup representing format attributes inside a specific paragraph or paragraph run
        /// </summary>
        /// <param name="document">Document to insert formatting Xml tags</param>
        /// <param name="xpathInsertionPoint">Paragraph or paragraph run to set format</param>
        /// <param name="content">Formatting tags</param>
        public static OpenXmlPowerToolsDocument Insert(WmlDocument doc, string xpathInsertionPoint, string content)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    XDocument xDocument = document.MainDocumentPart.GetXDocument();
                    XmlDocument xmlMainDocument = new XmlDocument();
                    xmlMainDocument.Load(xDocument.CreateReader());

                    XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());
                    namespaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");

                    XmlNodeList insertionPoints = xmlMainDocument.SelectNodes(xpathInsertionPoint, namespaceManager);

                    if (insertionPoints.Count == 0)
                        throw new ArgumentException("The xpath query did not return a valid location.");

                    foreach (XmlNode insertionPoint in insertionPoints)
                    {
                        XmlNode propertiesElement = insertionPoint.SelectSingleNode(@"w:pPr|w:rPr", namespaceManager);
                        if (insertionPoint.Name == "w:p")
                        {
                            // Checks if the rPr or pPr element exists
                            if (propertiesElement == null)
                            {
                                propertiesElement = xmlMainDocument.CreateElement("w", "pPr", namespaceManager.LookupNamespace("w"));
                                insertionPoint.PrependChild(propertiesElement);
                            }
                        }
                        else if (insertionPoint.Name == "w:r")
                        {
                            // Checks if the rPr or pPr element exists
                            if (propertiesElement == null)
                            {
                                propertiesElement = xmlMainDocument.CreateElement("w", "rPr", namespaceManager.LookupNamespace("w"));
                                insertionPoint.PrependChild(propertiesElement);
                            }
                        }

                        if (propertiesElement != null)
                        {
                            propertiesElement.InnerXml += content;
                        }
                        else
                        {
                            throw new ArgumentException("Specified xpath query result is not a valid location to place a formatting markup");
                        }

                    }
                    XDocument xNewDocument = new XDocument();
                    using (XmlWriter xWriter = xNewDocument.CreateWriter())
                        xmlMainDocument.WriteTo(xWriter);
                    document.MainDocumentPart.PutXDocument(xNewDocument);
                }
                return streamDoc.GetModifiedDocument();
            }
        }
        private static Stream _GetNewContact()
        {
            // The emptycontact.xml provides a basic template for a new contact.
            // Need to replace template data in it with unique data, e.g. ContactID/Value and CreationDate,
            //   before trying to load it as a contact.

            // Could keep reusing the same XmlDocument, but would need to guard it for multiple-thread access.
            var xmlDoc = new XmlDocument();
            _EmptyContactStream.Position = 0;
            xmlDoc.Load(_EmptyContactStream);

            var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
            nsmgr.AddNamespace("c", SchemaStrings.ContactNamespace);
            Assert.AreEqual(SchemaStrings.ContactNamespace, nsmgr.LookupNamespace("c"));

            var contactIdElement = xmlDoc.SelectSingleNode("./c:contact/c:ContactIDCollection/c:ContactID", nsmgr) as XmlElement;
            contactIdElement.SetAttribute(SchemaStrings.ElementId, SchemaStrings.ContactNamespace, Guid.NewGuid().ToString());
            var valueElement = contactIdElement.FirstChild as XmlElement;
            valueElement.InnerText = Guid.NewGuid().ToString();

            var creationDateElement = xmlDoc.SelectSingleNode("./c:contact/c:CreationDate", nsmgr) as XmlElement;
            creationDateElement.InnerText = XmlUtil.DateTimeNowString;

            Stream stm = new MemoryStream();
            xmlDoc.Save(stm);

            return stm;
        }
示例#4
0
 /// <summary>
 /// This function will set all content files to be embedded resources
 /// </summary>
 /// <param name="args">
 ///Command Line Arguments:
 /// 0 - Path to project file.
 /// </param>
 static void Main(string[] args)
 {
     string pathToProject = args[0];
     if (System.IO.File.Exists(pathToProject))
     {
         XmlDocument projectFile = new XmlDocument();
         projectFile.Load(pathToProject);
         XmlNamespaceManager nsMgr = new XmlNamespaceManager(projectFile.NameTable);
         nsMgr.AddNamespace("build", "http://schemas.microsoft.com/developer/msbuild/2003");
         XmlNodeList contentNodes = projectFile.SelectNodes("build:Project/build:ItemGroup/build:Content", nsMgr);
         bool wasProjectModified = false;
         foreach (XmlNode contentNode in contentNodes)
         {
             if (contentNode.Attributes["Include"] != null)
             {
                 string extension = System.IO.Path.GetExtension(contentNode.Attributes["Include"].Value);
                 if (!excludedExtensions.Contains(extension))
                 {
                     XmlNode resourceNode = projectFile.CreateElement("EmbeddedResource", nsMgr.LookupNamespace("build"));
                     XmlAttribute includeAttribute = projectFile.CreateAttribute("Include");
                     includeAttribute.Value = contentNode.Attributes["Include"].Value;
                     resourceNode.Attributes.Append(includeAttribute);
                     XmlNode parentNode = contentNode.ParentNode;
                     parentNode.ReplaceChild(resourceNode, contentNode);
                     wasProjectModified = true;
                 }
             }
         }
         if (wasProjectModified)
         {
             projectFile.Save(pathToProject);
         }
     }
 }
 private static string ParseXPathString(XPathLexer lexer, XmlNamespaceManager namespaceManager, bool throwOnFailure)
 {
     int firstTokenChar = lexer.FirstTokenChar;
     if (lexer.MoveNext())
     {
         XPathToken token = lexer.Token;
         StringBuilder builder = new StringBuilder(ParseXPathString(lexer, namespaceManager, throwOnFailure));
         if (XPathTokenID.NameTest == token.TokenID)
         {
             string prefix = token.Prefix;
             if (!string.IsNullOrEmpty(prefix))
             {
                 string str3 = namespaceManager.LookupNamespace(prefix);
                 if (!string.IsNullOrEmpty(str3))
                 {
                     builder = builder.Replace(prefix, str3, firstTokenChar, prefix.Length);
                 }
                 else if (throwOnFailure)
                 {
                     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new IndexOutOfRangeException(System.ServiceModel.SR.GetString("ConfigXPathNamespacePrefixNotFound", new object[] { prefix })));
                 }
             }
         }
         return builder.ToString();
     }
     return lexer.ConsumedSubstring();
 }
示例#6
0
 public void AddFile(byte[] data, string path)
 {
     XmlDocument manifest = GetXMLDocument ("META-INF/manifest.xml");
     XmlNamespaceManager nsManager = new XmlNamespaceManager (manifest.NameTable);
     nsManager.AddNamespace ("manifest", "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0");
     XmlNode manifestNode = manifest.SelectSingleNode("/manifest:manifest",nsManager);
     XmlElement fileEntry = manifest.CreateElement ("manifest", "file-entry", nsManager.LookupNamespace("manifest"));
     fileEntry.SetAttribute ("full-path", nsManager.LookupNamespace ("manifest"),path);
     fileEntry.SetAttribute ("media-type", nsManager.LookupNamespace ("manifest"), "image/png");
     manifestNode.AppendChild(fileEntry);
     using (var fileStream = new MemoryStream (data)) {
         odtZip.BeginUpdate ();
         StreamStaticDataSource sds = new StreamStaticDataSource ();
         sds.SetStream (fileStream);
         odtZip.Add (sds, path);
         odtZip.CommitUpdate ();
     }
     UpdateXmlDocument (manifest, "META-INF/manifest.xml");
 }
 public Description(XmlNode elm, XmlNamespaceManager nsmgr)
 {
     string asmv2 = nsmgr.LookupNamespace("asmv2");
     if (elm.Attributes["publisher", asmv2] != null)
         Publisher = elm.Attributes["publisher", asmv2].Value;
     if (elm.Attributes["product", asmv2] != null)
         Product = elm.Attributes["product", asmv2].Value;
     if (elm.Attributes["supportUrl", asmv2] != null)
         SupportUrl = new Uri(elm.Attributes["supportUrl", asmv2].Value);
 }
示例#8
0
文件: Util.cs 项目: sunpander/VSDT
 public static XmlElement CreateElement(XmlElement parent, string name, string innerText, XmlNamespaceManager nsMgr)
 {
     if (parent == null)
     {
         throw new Exception("Passed in a null node, which should never happen.  Tell Gus!");
     }
     XmlElement newChild = parent.OwnerDocument.CreateElement(name, nsMgr.LookupNamespace("ns1"));
     XmlElement element2 = (XmlElement) parent.AppendChild(newChild);
     element2.InnerText = innerText;
     return (XmlElement) parent.AppendChild(element2);
 }
示例#9
0
        /// <summary>
        /// Gets a named attribute value of an xml element
        /// </summary>
        /// <param name="xml">The xml node</param>
        /// <param name="attribute">The attribute name. It could be of prefix:localname form</param>
        /// <param name="nsResolver">The Xml namespace resolver object</param>
        /// <returns>The value of named attribute if found; null otherwise</returns>
        public static string GetAttributeValue(this XElement xml, string attribute, XmlNamespaceManager nsResolver)
        {
            string fullName = attribute;
            string[] name = attribute.Split(new char[]{':'}, 2);
            if (name != null && name.Length == 2)
            {
                var ns = nsResolver.LookupNamespace(name[0]);
                fullName = string.Format("{{{0}}}{1}", ns, name[1]);
            }

            return GetAttributeValue(xml, fullName);
        }
示例#10
0
		public Xml2Xsd(System.Xml.XmlNameTable tableName)
		{
			// initialize code here
			nsmgr = new XmlNamespaceManager(tableName);
			nsmgr.AddNamespace("xsd", schemaNS);
			nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
			nsmgr.AddNamespace("msdata", "urn:schemas-microsoft-com:xml-msdata");

			foreach (String prefix in nsmgr)
			{
				XmlNS.Add(prefix, nsmgr.LookupNamespace(prefix));
			}
		}
示例#11
0
		public static XmlNode GetOrCreateElement(XmlNode node, string xpathNotIncludingElement,
			string elementName, string nameSpace, XmlNamespaceManager nameSpaceManager, IComparer<XmlNode> nodeOrderComparer)
		{
			//enhance: if the parent path isn't found, strip of the last piece and recurse,
			//so that the path will always be created if needed.

			XmlNode parentNode = node.SelectSingleNode(xpathNotIncludingElement,nameSpaceManager);
			if (parentNode == null)
			{
				throw new ApplicationException(string.Format("The path {0} could not be found", xpathNotIncludingElement));
			}
			string prefix = "";
			if (!String.IsNullOrEmpty(nameSpace))
			{
				prefix = nameSpace + ":";
			}
			XmlNode n = parentNode.SelectSingleNode(prefix+elementName,nameSpaceManager);
			if (n == null)
			{
				if (!String.IsNullOrEmpty(nameSpace))
				{
					n = GetDocument(node).CreateElement(nameSpace, elementName, nameSpaceManager.LookupNamespace(nameSpace));
				}
				else
				{
					n = GetDocument(node).CreateElement(elementName);
				}
				if (nodeOrderComparer == null)
				{
					parentNode.AppendChild(n);
				}
				else
				{
					XmlNode insertAfterNode = null;
					foreach (XmlNode childNode in parentNode.ChildNodes)
					{
						if (childNode.NodeType != XmlNodeType.Element)
						{
							continue;
						}
						if (nodeOrderComparer.Compare(n, childNode) < 0)
						{
							break;
						}
						insertAfterNode = childNode;
					}
					parentNode.InsertAfter(n, insertAfterNode);
				}
			}
			return n;
		}
示例#12
0
文件: Util.cs 项目: sunpander/VSDT
 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);
 }
 internal NamespaceQualifiedValue(XmlNamespaceManager NamespaceManager, string FullyQualifiedValue)
 {
     thisFullyQualifiedValue = FullyQualifiedValue;
     thisFullyQualifiedValueComponents = thisFullyQualifiedValue.Split(':');
     if (thisFullyQualifiedValueComponents.Length == 1)
     {
         thisLocalName = thisFullyQualifiedValueComponents[0];
         thisNamespace = string.Empty;
         thisNamespaceUri = string.Empty;
     }
     else
     {
         thisLocalName = thisFullyQualifiedValueComponents[1];
         thisNamespace = thisFullyQualifiedValueComponents[0];
         thisNamespaceUri = NamespaceManager.LookupNamespace(thisNamespace);
     }
 }
示例#14
0
		/// <summary>
		/// Initializes a new instance of the <see cref="DynamicContext"/> class.
		/// </summary>
		/// <param name="context">A previously filled context with the namespaces to use.</param>
		/// <param name="table">The NameTable to use.</param>
		public DynamicContext(XmlNamespaceManager context, NameTable table) : base(table)
		{
			object xml = table.Add(XmlNamespaces.Xml);
			object xmlns = table.Add(XmlNamespaces.XmlNs);

			if (context != null)
			{
				foreach (string prefix in context)
				{
					string uri = context.LookupNamespace(prefix);
					// Use fast object reference comparison to omit forbidden namespace declarations.
					if (Object.Equals(uri, xml) || Object.Equals(uri, xmlns))
						continue;

					base.AddNamespace(prefix, uri);
				}
			}
		}
示例#15
0
		private void InitNamespaceManager(bool isHtmlDocument)
		{
            this.XmlNamespaceManager = new XmlNamespaceManager(XPathNavigator.NameTable);

            if (isHtmlDocument)
            {
                string ns = XmlNamespaceManager.LookupNamespace("xmlns");
                if (!string.IsNullOrEmpty(ns))
                {
                }
            }
            else
            {
                XPathNodeIterator iterator = XPathNavigator.Select("//namespace::*[not(. = ../../namespace::*)]");

                while (iterator.MoveNext())
                {
                    XmlNamespaceManager.AddNamespace(iterator.Current.Name, iterator.Current.Value);
                }
            }
		}
示例#16
0
 internal static XmlElement GetOrCreateElement(this XmlElement parentElement, string prefix, string elementName, XmlNamespaceManager nsm, bool insertBefore, XmlNode refNode)
 {
     XmlElement elem = (XmlElement)parentElement.SelectSingleNode(prefix + ":" + elementName, nsm);
     if (elem == null)
     {
         elem = parentElement.OwnerDocument.CreateElement(elementName, nsm.LookupNamespace(prefix));
         if (insertBefore == true && refNode != null)
         {
             parentElement.InsertBefore(elem, refNode);
         }
         else if (insertBefore == false && refNode != null)
         {
             parentElement.InsertAfter(elem, refNode);
         }
         else
         {
             parentElement.AppendChild(elem);
         }
     }
     return elem;
 }
        static string ParseXPathString(XPathLexer lexer, XmlNamespaceManager namespaceManager, bool throwOnFailure)
        {
            string retVal = String.Empty;

            int currentTokenStart = lexer.FirstTokenChar;
            if (lexer.MoveNext())
            {
                XPathToken token = lexer.Token;
                StringBuilder xPathString = new StringBuilder(XPathMessageFilterElementComparer.ParseXPathString(lexer, namespaceManager, throwOnFailure));

                if (XPathTokenID.NameTest == token.TokenID)
                {
                    string nsPrefix = token.Prefix;
                    if (!String.IsNullOrEmpty(nsPrefix))
                    {
                        string ns = namespaceManager.LookupNamespace(nsPrefix);
                        if (!String.IsNullOrEmpty(ns))
                        {
                            xPathString = xPathString.Replace(nsPrefix, ns, currentTokenStart, nsPrefix.Length);
                        }
                        else
                        {
                            if (throwOnFailure)
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new IndexOutOfRangeException(SR.GetString(SR.ConfigXPathNamespacePrefixNotFound, nsPrefix)));
                            }
                        }
                    }
                }

                retVal = xPathString.ToString();
            }
            else
            {
                retVal = lexer.ConsumedSubstring();
            }

            return retVal;
        }
示例#18
0
        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;
                }
            }
        }
示例#19
0
    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();

              if (!string.IsNullOrEmpty(attributeName))
              {
                char firstChar = attributeName[0];
                string attributeValue;

                switch (firstChar)
                {
                  case '@':
                    attributeName = attributeName.Substring(1);
                    reader.Read();
                    attributeValue = ConvertTokenToXmlValue(reader);
                    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 (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?')
          {
            if (propertyName == DeclarationName)
            {
              string version = null;
              string encoding = null;
              string standalone = null;
              while (reader.Read() && reader.TokenType != JsonToken.EndObject)
              {
                switch (reader.Value.ToString())
                {
                  case "@version":
                    reader.Read();
                    version = reader.Value.ToString();
                    break;
                  case "@encoding":
                    reader.Read();
                    encoding = reader.Value.ToString();
                    break;
                  case "@standalone":
                    reader.Read();
                    standalone = reader.Value.ToString();
                    break;
                  default:
                    throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value);
                }
              }

              XmlDeclaration declaration = document.CreateXmlDeclaration(version, encoding, standalone);
              currentNode.AppendChild(declaration);
            }
            else
            {
              XmlProcessingInstruction instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString());
              currentNode.AppendChild(instruction);
            }
          }
          else
          {
            // deserialize xml element
            bool finishedAttributes = false;
            bool finishedElement = false;
            string elementPrefix = GetPrefix(propertyName);
            Dictionary<string, string> attributeNameValues = new Dictionary<string, string>();

            // a string token means the element only has a single text child
            if (reader.TokenType != JsonToken.String
              && reader.TokenType != JsonToken.Null
              && reader.TokenType != JsonToken.Boolean
              && reader.TokenType != JsonToken.Integer
              && reader.TokenType != JsonToken.Float
              && reader.TokenType != JsonToken.Date
              && reader.TokenType != JsonToken.StartConstructor)
            {
              // read properties until first non-attribute is encountered
              while (!finishedAttributes && !finishedElement && reader.Read())
              {
                switch (reader.TokenType)
                {
                  case JsonToken.PropertyName:
                    string attributeName = reader.Value.ToString();

                    if (attributeName[0] == '@')
                    {
                      attributeName = attributeName.Substring(1);
                      reader.Read();
                      string attributeValue = reader.Value.ToString();
                      attributeNameValues.Add(attributeName, attributeValue);

                      string namespacePrefix;

                      if (IsNamespaceAttribute(attributeName, out namespacePrefix))
                      {
                        manager.AddNamespace(namespacePrefix, attributeValue);
                      }
                    }
                    else
                    {
                      finishedAttributes = true;
                    }
                    break;
                  case JsonToken.EndObject:
                    finishedElement = true;
                    break;
                  default:
                    throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType);
                }
              }
            }

            // have to wait until attributes have been parsed before creating element
            // attributes may contain namespace info used by the element
            XmlElement element = (!string.IsNullOrEmpty(elementPrefix))
                    ? document.CreateElement(propertyName, manager.LookupNamespace(elementPrefix))
                    : document.CreateElement(propertyName);

            currentNode.AppendChild(element);

            // add attributes to newly created element
            foreach (KeyValuePair<string, string> nameValue in attributeNameValues)
            {
              string attributePrefix = GetPrefix(nameValue.Key);

              XmlAttribute attribute = (!string.IsNullOrEmpty(attributePrefix))
                      ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix))
                      : document.CreateAttribute(nameValue.Key);

              attribute.Value = nameValue.Value;

              element.SetAttributeNode(attribute);
            }

            if (reader.TokenType == JsonToken.String)
            {
              element.AppendChild(document.CreateTextNode(reader.Value.ToString()));
            }
            else if (reader.TokenType == JsonToken.Integer)
            {
              element.AppendChild(document.CreateTextNode(XmlConvert.ToString((long)reader.Value)));
            }
            else if (reader.TokenType == JsonToken.Float)
            {
              element.AppendChild(document.CreateTextNode(XmlConvert.ToString((double)reader.Value)));
            }
            else if (reader.TokenType == JsonToken.Boolean)
            {
              element.AppendChild(document.CreateTextNode(XmlConvert.ToString((bool)reader.Value)));
            }
            else if (reader.TokenType == JsonToken.Date)
            {
              DateTime d = (DateTime)reader.Value;
              element.AppendChild(document.CreateTextNode(XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind))));
            }
            else if (reader.TokenType == JsonToken.Null)
            {
              // empty element. do nothing
            }
            else
            {
              // finished element will have no children to deserialize
              if (!finishedElement)
              {
                manager.PushScope();

                DeserializeNode(reader, document, manager, element);

                manager.PopScope();
              }
            }
          }
          break;
      }
    }
示例#21
0
    private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager)
    {
      if (string.IsNullOrEmpty(propertyName))
        throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML.");

      Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager);

      string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);

      if (propertyName.StartsWith("@"))
      {
        var attributeName = propertyName.Substring(1);
        var attributeValue = reader.Value.ToString();

        var attributePrefix = MiscellaneousUtils.GetPrefix(attributeName);

        var attribute = (!string.IsNullOrEmpty(attributePrefix))
                                 ? document.CreateAttribute(attributeName, manager.LookupNamespace(attributePrefix), attributeValue)
                                 : document.CreateAttribute(attributeName, attributeValue);

        ((IXmlElement)currentNode).SetAttributeNode(attribute);
      }
      else
      {
        IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager);

        currentNode.AppendChild(element);

        // add attributes to newly created element
        foreach (KeyValuePair<string, string> nameValue in attributeNameValues)
        {
          string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key);

          IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix))
                                 ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix), nameValue.Value)
                                 : document.CreateAttribute(nameValue.Key, nameValue.Value);

          element.SetAttributeNode(attribute);
        }

        if (reader.TokenType == JsonToken.String
            || reader.TokenType == JsonToken.Integer
            || reader.TokenType == JsonToken.Float
            || reader.TokenType == JsonToken.Boolean
            || reader.TokenType == JsonToken.Date)
        {
          element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader)));
        }
        else if (reader.TokenType == JsonToken.Null)
        {
          // empty element. do nothing
        }
        else
        {
          // finished element will have no children to deserialize
          if (reader.TokenType != JsonToken.EndObject)
          {
            manager.PushScope();

            DeserializeNode(reader, document, manager, element);

            manager.PopScope();
          }
        }
      }
    }
示例#22
0
		// Note that this must be done *before* filtering nodes out
		// by context node list.
		private void FillMissingPrefixes (XmlNode n, XmlNamespaceManager nsmgr, ArrayList tmpList)
		{
			if (n.Prefix.Length == 0 && propagatedNss != null) {
				foreach (DictionaryEntry de in propagatedNss)
					if ((string) de.Value == n.NamespaceURI) {
						n.Prefix = (string) de.Key;
						break;
					}
			}
			
			if (n.NodeType == XmlNodeType.Element && ((XmlElement) n).HasAttributes) {
				foreach (XmlAttribute a in n.Attributes)
					if (a.NamespaceURI == "http://www.w3.org/2000/xmlns/")
						nsmgr.AddNamespace (a.Prefix.Length == 0 ? String.Empty : a.LocalName, a.Value);
				nsmgr.PushScope ();
			}

			if (n.NamespaceURI.Length > 0 && nsmgr.LookupPrefix (n.NamespaceURI) == null)
				tmpList.Add (CreateXmlns (n));

			if (n.NodeType == XmlNodeType.Element && ((XmlElement) n).HasAttributes) {
				foreach (XmlAttribute a in n.Attributes)
					if (a.NamespaceURI.Length > 0 && nsmgr.LookupNamespace (a.Prefix) == null)
						tmpList.Add (CreateXmlns (a));
			}

			foreach (XmlAttribute a in tmpList)
				((XmlElement) n).SetAttributeNode (a);
			tmpList.Clear ();

			if (n.HasChildNodes) {
				for (XmlNode c = n.FirstChild; c != null; c = c.NextSibling)
					if (c.NodeType == XmlNodeType.Element)
						FillMissingPrefixes (c, nsmgr, tmpList);
			}
			nsmgr.PopScope ();
		}
示例#23
0
文件: XmlNode.cs 项目: nekresh/mono
		// It parses this and all the ancestor elements,
		// find 'xmlns' declarations, stores and then return them.
		internal XmlNamespaceManager ConstructNamespaceManager ()
		{
			XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
			XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
			XmlElement el = null;
			switch(this.NodeType) {
			case XmlNodeType.Attribute:
				el = ((XmlAttribute)this).OwnerElement;
				break;
			case XmlNodeType.Element:
				el = this as XmlElement;
				break;
			default:
				el = this.ParentNode as XmlElement;
				break;
			}

			while (el != null) {
				for (int i = 0; i < el.Attributes.Count; i++) {
					XmlAttribute attr = el.Attributes [i];
					if(attr.Prefix == "xmlns") {
						if (nsmgr.LookupNamespace (attr.LocalName) != attr.Value)
							nsmgr.AddNamespace (attr.LocalName, attr.Value);
					} else if(attr.Name == "xmlns") {
						if(nsmgr.LookupNamespace (String.Empty) != attr.Value)
							nsmgr.AddNamespace (String.Empty, attr.Value);
					}
				}
				// When reached to document, then it will set null value :)
				el = el.ParentNode as XmlElement;
			}
			return nsmgr;
		}
示例#24
0
        private void InitFragmentReader(XmlNodeType fragmentType, XmlParserContext parserContext, bool allowXmlDeclFragment)
        {
            _fragmentParserContext = parserContext;

            if (parserContext != null)
            {
                if (parserContext.NamespaceManager != null)
                {
                    _namespaceManager = parserContext.NamespaceManager;
                    _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty);
                }
                else
                {
                    _namespaceManager = new XmlNamespaceManager(_nameTable);
                }

                _ps.baseUriStr = parserContext.BaseURI;
                _ps.baseUri = null;
                _xmlContext.xmlLang = parserContext.XmlLang;
                _xmlContext.xmlSpace = parserContext.XmlSpace;
            }
            else
            {
                _namespaceManager = new XmlNamespaceManager(_nameTable);
                _ps.baseUriStr = string.Empty;
                _ps.baseUri = null;
            }

            _reportedBaseUri = _ps.baseUriStr;

            switch (fragmentType)
            {
                case XmlNodeType.Attribute:
                    _ps.appendMode = false;
                    _parsingFunction = ParsingFunction.SwitchToInteractive;
                    _nextParsingFunction = ParsingFunction.FragmentAttribute;
                    break;
                case XmlNodeType.Element:
                    Debug.Assert(_parsingFunction == ParsingFunction.SwitchToInteractiveXmlDecl);
                    _nextParsingFunction = ParsingFunction.DocumentContent;
                    break;
                case XmlNodeType.Document:
                    Debug.Assert(_parsingFunction == ParsingFunction.SwitchToInteractiveXmlDecl);
                    Debug.Assert(_nextParsingFunction == ParsingFunction.DocumentContent);
                    break;
                case XmlNodeType.XmlDeclaration:
                    if (allowXmlDeclFragment)
                    {
                        _ps.appendMode = false;
                        _parsingFunction = ParsingFunction.SwitchToInteractive;
                        _nextParsingFunction = ParsingFunction.XmlDeclarationFragment;
                        break;
                    }
                    else
                    {
                        goto default;
                    }
                default:
                    Throw(SR.Xml_PartialContentNodeTypeNotSupportedEx, fragmentType.ToString());
                    return;
            }
            _fragmentType = fragmentType;
            _fragment = true;
        }
示例#25
0
        private void SetupFromParserContext(XmlParserContext context, XmlReaderSettings settings)
        {
            Debug.Assert(context != null);

            // setup nameTable
            XmlNameTable nt = settings.NameTable;
            _nameTableFromSettings = (nt != null);

            // get name table from namespace manager in XmlParserContext, if available; 
            if (context.NamespaceManager != null)
            {
                // must be the same as XmlReaderSettings.NameTable, or null
                if (nt != null && nt != context.NamespaceManager.NameTable)
                {
                    throw new XmlException(SR.Xml_NametableMismatch);
                }
                // get the namespace manager from context
                _namespaceManager = context.NamespaceManager;
                _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty);

                // get the nametable from ns manager
                nt = _namespaceManager.NameTable;

                Debug.Assert(nt != null);
                Debug.Assert(context.NameTable == null || context.NameTable == nt, "This check should have been done in XmlParserContext constructor.");
            }
            // get name table directly from XmlParserContext
            else if (context.NameTable != null)
            {
                // must be the same as XmlReaderSettings.NameTable, or null
                if (nt != null && nt != context.NameTable)
                {
                    throw new XmlException(SR.Xml_NametableMismatch, string.Empty);
                }
                nt = context.NameTable;
            }
            // no nametable provided -> create a new one
            else if (nt == null)
            {
                nt = new NameTable();
                Debug.Assert(_nameTableFromSettings == false);
            }
            _nameTable = nt;

            // make sure we have namespace manager
            if (_namespaceManager == null)
            {
                _namespaceManager = new XmlNamespaceManager(nt);
            }

            // copy xml:space and xml:lang
            _xmlContext.xmlSpace = context.XmlSpace;
            _xmlContext.xmlLang = context.XmlLang;
        }
 private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager)
 {
   return (!string.IsNullOrEmpty(elementPrefix))
            ? document.CreateElement(elementName, manager.LookupNamespace(elementPrefix))
            : document.CreateElement(elementName);
 }
示例#27
0
        private void ParseDtdFromParserContext() {
            Debug.Assert( dtdInfo == null && fragmentParserContext != null && fragmentParserContext.HasDtdInfo );

            IDtdParser dtdParser = DtdParser.Create();

            // Parse DTD
            dtdInfo = dtdParser.ParseFreeFloatingDtd(fragmentParserContext.BaseURI, fragmentParserContext.DocTypeName, fragmentParserContext.PublicId,
                                                     fragmentParserContext.SystemId, fragmentParserContext.InternalSubset, new DtdParserProxy( this ) );

#if SILVERLIGHT // Needed only for XmlTextReader or XmlValidatingReader
            if (dtdInfo.HasDefaultAttributes || dtdInfo.HasNonCDataAttributes) {
#else
            if ( ( validatingReaderCompatFlag || !v1Compat ) && ( dtdInfo.HasDefaultAttributes || dtdInfo.HasNonCDataAttributes ) ) {
#endif
                addDefaultAttributesAndNormalize = true;
            }
        }

        bool InitReadContentAsBinary() {
            Debug.Assert( parsingFunction != ParsingFunction.InReadContentAsBinary );

            if ( parsingFunction == ParsingFunction.InReadValueChunk ) {
                throw new InvalidOperationException( Res.GetString( Res.Xml_MixingReadValueChunkWithBinary ) );
            }
            if ( parsingFunction == ParsingFunction.InIncrementalRead ) {
                throw new InvalidOperationException( Res.GetString( Res.Xml_MixingV1StreamingWithV2Binary ) );
            }

            if ( !XmlReader.IsTextualNode( curNode.type ) ) {
                if ( !MoveToNextContentNode( false ) ) {
                    return false;
                }
            }

            SetupReadContentAsBinaryState( ParsingFunction.InReadContentAsBinary );
            incReadLineInfo.Set( curNode.LineNo, curNode.LinePos );
            return true;
        }

        bool InitReadElementContentAsBinary() {
            Debug.Assert( parsingFunction != ParsingFunction.InReadElementContentAsBinary );
            Debug.Assert( curNode.type == XmlNodeType.Element );

            bool isEmpty = curNode.IsEmptyElement;

            // move to content or off the empty element
            outerReader.Read();
            if ( isEmpty ) {
                return false;
            }

            // make sure we are on a content node
            if ( !MoveToNextContentNode( false ) ) {
                if ( curNode.type != XmlNodeType.EndElement ) {
                    Throw( Res.Xml_InvalidNodeType, curNode.type.ToString() );
                }
                // move off end element
                outerReader.Read();
                return false;
            }
            SetupReadContentAsBinaryState( ParsingFunction.InReadElementContentAsBinary );
            incReadLineInfo.Set( curNode.LineNo, curNode.LinePos );
            return true;
        }

        bool MoveToNextContentNode( bool moveIfOnContentNode ) {
            do {
                switch ( curNode.type ) {
                    case XmlNodeType.Attribute:
                        return !moveIfOnContentNode;
                    case XmlNodeType.Text:
                    case XmlNodeType.Whitespace:
                    case XmlNodeType.SignificantWhitespace:
                    case XmlNodeType.CDATA:
                        if ( !moveIfOnContentNode ) {
                            return true;
                        }
                        break;
                    case XmlNodeType.ProcessingInstruction:
                    case XmlNodeType.Comment:
                    case XmlNodeType.EndEntity:
                        // skip comments, pis and end entity nodes
                        break;
                    case XmlNodeType.EntityReference:
                        outerReader.ResolveEntity();
                        break;
                    default:
                        return false;
                }
                moveIfOnContentNode = false;
            } while ( outerReader.Read() );
            return false;
        }

        void SetupReadContentAsBinaryState( ParsingFunction inReadBinaryFunction ) {
            if ( parsingFunction == ParsingFunction.PartialTextValue ) {
                incReadState = IncrementalReadState.ReadContentAsBinary_OnPartialValue;
            }
            else {
                incReadState = IncrementalReadState.ReadContentAsBinary_OnCachedValue;
                nextNextParsingFunction = nextParsingFunction;
                nextParsingFunction = parsingFunction;
            }
            readValueOffset = 0;
            parsingFunction = inReadBinaryFunction;
        }

        void SetupFromParserContext( XmlParserContext context, XmlReaderSettings settings ) {
            Debug.Assert( context != null );

            // setup nameTable
            XmlNameTable nt = settings.NameTable;
            nameTableFromSettings = ( nt != null );

            // get name table from namespace manager in XmlParserContext, if available; 
            if ( context.NamespaceManager != null ) {
                // must be the same as XmlReaderSettings.NameTable, or null
                if ( nt != null && nt != context.NamespaceManager.NameTable ) {
                    throw new XmlException( Res.Xml_NametableMismatch );
                }
                // get the namespace manager from context
                namespaceManager = context.NamespaceManager;
                xmlContext.defaultNamespace = namespaceManager.LookupNamespace( string.Empty );

                // get the nametable from ns manager
                nt = namespaceManager.NameTable;

                Debug.Assert( nt != null );
                Debug.Assert( context.NameTable == null || context.NameTable == nt, "This check should have been done in XmlParserContext constructor." );
            } 
            // get name table directly from XmlParserContext
            else if ( context.NameTable != null ) {
                // must be the same as XmlReaderSettings.NameTable, or null
                if ( nt != null && nt != context.NameTable ) {
                    throw new XmlException( Res.Xml_NametableMismatch, string.Empty );
                }
                nt = context.NameTable;
            }
            // no nametable provided -> create a new one
            else if ( nt == null ) {
                nt = new NameTable();
                Debug.Assert( nameTableFromSettings == false );
            }
            nameTable = nt;

            // make sure we have namespace manager
            if ( namespaceManager == null ) {
                namespaceManager = new XmlNamespaceManager( nt );
            }

            // copy xml:space and xml:lang
            xmlContext.xmlSpace = context.XmlSpace;
            xmlContext.xmlLang = context.XmlLang;
        }
        private void RemoveDuplicateNamespace(XmlElement elem, XmlNamespaceManager mgr, bool fCheckElemAttrs)
        {
            //remove the duplicate attributes on current node first
            mgr.PushScope();
            XmlAttributeCollection attrs = elem.Attributes;
            int cAttrs = attrs.Count;

            if (fCheckElemAttrs && cAttrs > 0)
            {
                for (int i = cAttrs - 1; i >= 0; --i)
                {
                    XmlAttribute attr = attrs[i];
                    if (attr.Prefix == doc.strXmlns)
                    {
                        string nsUri = mgr.LookupNamespace(attr.LocalName);
                        if (nsUri != null)
                        {
                            if (attr.Value == nsUri)
                            {
                                elem.Attributes.RemoveNodeAt(i);
                            }
                        }
                        else
                        {
                            // Add this namespace, so it we will behave corectly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as
                            // InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>"
                            // If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for
                            // the subsequent InnerXml_set or setting an EntRef inside.
                            mgr.AddNamespace(attr.LocalName, attr.Value);
                        }
                    }
                    else if (attr.Prefix.Length == 0 && attr.LocalName == doc.strXmlns)
                    {
                        string nsUri = mgr.DefaultNamespace;
                        if (nsUri != null)
                        {
                            if (attr.Value == nsUri)
                            {
                                elem.Attributes.RemoveNodeAt(i);
                            }
                        }
                        else
                        {
                            // Add this namespace, so it we will behave corectly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as
                            // InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>"
                            // If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for
                            // the subsequent InnerXml_set or setting an EntRef inside.
                            mgr.AddNamespace(attr.LocalName, attr.Value);
                        }
                    }
                }
            }
            //now recursively remove the duplicate attributes on the children
            XmlNode child = elem.FirstChild;

            while (child != null)
            {
                XmlElement childElem = child as XmlElement;
                if (childElem != null)
                {
                    RemoveDuplicateNamespace(childElem, mgr, true);
                }
                child = child.NextSibling;
            }
            mgr.PopScope();
        }
示例#29
0
    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;
    }
示例#30
0
        public void Write(System.Xml.XmlWriter writer, System.Xml.XmlNamespaceManager namespaceManager)
        {
            XmlSerializerNamespaces nss = new XmlSerializerNamespaces();

            if (namespaceManager != null)
            {
                foreach (string name in namespaceManager)
                {
                    //xml and xmlns namespaces are added by default in namespaceManager.
                    //So we should ignore them
                    if (name != "xml" && name != "xmlns")
                    {
                        nss.Add(name, namespaceManager.LookupNamespace(name));
                    }
                }
            }

            if (Namespaces != null && Namespaces.Count > 0)
            {
                XmlQualifiedName [] qnames = Namespaces.ToArray();
                foreach (XmlQualifiedName qn in qnames)
                {
                    nss.Add(qn.Name, qn.Namespace);
                }
                string p    = String.Empty;
                bool   loop = true;
                for (int idx = 1; loop; idx++)
                {
                    loop = false;
                    foreach (XmlQualifiedName qn in qnames)
                    {
                        if (qn.Name == p)
                        {
                            p    = "q" + idx;
                            loop = true;
                            break;
                        }
                    }
                }
                nss.Add(p, XmlSchema.Namespace);
            }

            if (nss.Count == 0)
            {
                // Add the xml schema namespace. (It is done
                // only when no entry exists in Namespaces).
                nss.Add("xs", XmlSchema.Namespace);
                if (TargetNamespace != null && TargetNamespace.Length != 0)
                {
                    nss.Add("tns", TargetNamespace);
                }
            }

            XmlSchemaSerializer     xser   = new XmlSchemaSerializer();
            XmlSerializerNamespaces backup = Namespaces;

            try {
                Namespaces = null;
                xser.Serialize(writer, this, nss);
            } finally {
                Namespaces = backup;
            }
            writer.Flush();
        }
示例#31
0
 string IXmlNamespaceResolver.LookupNamespace(string prefix)
 {
     return(_namespaceManager.LookupNamespace(prefix));
 }
        public bool ApplyToContent(string rootFolder)
        {
            string fullPath = rootFolder + @"\AppxManifest.xml";

            if (!File.Exists(fullPath))
            {
                return(false);
            }

            var document = new XmlDocument();

            document.XmlResolver = null;
            using (var reader = new XmlTextReader(fullPath))
            {
                reader.DtdProcessing = DtdProcessing.Ignore;
                document.Load(reader);
            }

            var xmlnsManager = new System.Xml.XmlNamespaceManager(document.NameTable);

            xmlnsManager.AddNamespace("std", "http://schemas.microsoft.com/appx/manifest/foundation/windows10");
            xmlnsManager.AddNamespace("mp", "http://schemas.microsoft.com/appx/2014/phone/manifest");
            xmlnsManager.AddNamespace("uap", "http://schemas.microsoft.com/appx/manifest/uap/windows10");
            xmlnsManager.AddNamespace("iot", "http://schemas.microsoft.com/appx/manifest/iot/windows10");
            xmlnsManager.AddNamespace("build", "http://schemas.microsoft.com/developer/appx/2015/build");

            var capability = Capability;

            if (capability == null)
            {
                if (CapabilityNamespace != null)
                {
                    capability = CapabilityNamespace + ":Capability";
                }
                else
                {
                    capability = "Capability";
                }
            }
            else
            {
                if (CapabilityNamespace != null)
                {
                    capability = CapabilityNamespace + ":" + Capability;
                }
                else
                {
                    capability = Capability;
                }
            }

            var capabilitiesNode = document.SelectSingleNode(@"/std:Package/std:Capabilities", xmlnsManager);
            var newCapability    = document.CreateElement(capability, (CapabilityNamespace == null) ? document.DocumentElement.NamespaceURI : xmlnsManager.LookupNamespace(CapabilityNamespace));

            var capabilityNameAttribute = document.CreateAttribute("Name");

            capabilityNameAttribute.Value = CapabilityName;

            if (DeviceId != null)
            {
                var deviceNode            = document.CreateElement("Device", document.DocumentElement.NamespaceURI);
                var deviceIdNameAttribute = document.CreateAttribute("Id");
                deviceIdNameAttribute.Value = DeviceId;

                deviceNode.Attributes.Append(deviceIdNameAttribute);

                if (FunctionType != null)
                {
                    var functionNode          = document.CreateElement("Function", document.DocumentElement.NamespaceURI);
                    var functionTypeAttribute = document.CreateAttribute("Type");
                    functionTypeAttribute.Value = FunctionType;

                    functionNode.Attributes.Append(functionTypeAttribute);

                    deviceNode.AppendChild(functionNode);
                }

                newCapability.AppendChild(deviceNode);
            }

            newCapability.Attributes.Append(capabilityNameAttribute);
            capabilitiesNode.AppendChild(newCapability);


            document.Save(fullPath);
            return(true);
        }
示例#33
0
	// Update the search and namespace information.
	public void UpdateInfo(XmlNameTable nt, XmlNamespaceManager nm)
			{
				this.nt = nt;
				this.nm = nm;
				names.Clear();

				for(int i = 0; i < count; ++i)
				{
					// get the attribute name information
					AttributeInfo info = (AttributeInfo)attributes[i];
					String name = info.Name;

					// set the defaults
					String localName = name;
					String prefix = String.Empty;
					String namespaceURI = String.Empty;

					// find the namespace separator
					int index = name.LastIndexOf(':');

					// give an error if there's no name before the separator
					if(index == 0)
					{
						Error(/* TODO */);
					}

					// set the namespace information
					if(index > 0)
					{
						// add the prefix and local name to the name table
						prefix = nt.Add(name.Substring(0, index));
						localName = nt.Add(name.Substring(index + 1));

						// check for a valid prefix
						if(prefix.IndexOf(':') != -1)
						{
							Error(/* TODO */);
						}

						// set the namespace uri based on the prefix
						namespaceURI = nm.LookupNamespace(prefix);
					}
					else if(localName == "xmlns")
					{
						namespaceURI = nt.Add(XmlDocument.xmlns);
					}

					// create the key
					Key key = new Key(localName, namespaceURI);

					// check for duplicate
					if(names.ContainsKey(key))
					{
						Error(/* TODO */);
					}

					// add the key and index to the hash table
					names.Add(key, i);

					// update the current attribute's namespace information
					info.UpdateNamespaceInfo(localName, namespaceURI, prefix);
				}
			}
示例#34
0
 private void RemoveDuplicateNamespace(XmlElement elem, XmlNamespaceManager mgr, bool fCheckElemAttrs)
 {
     //remove the duplicate attributes on current node first
     mgr.PushScope();
     XmlAttributeCollection attrs = elem.Attributes;
     int cAttrs = attrs.Count;
     if (fCheckElemAttrs && cAttrs > 0)
     {
         for (int i = cAttrs - 1; i >= 0; --i)
         {
             XmlAttribute attr = attrs[i];
             if (attr.Prefix == _doc.strXmlns)
             {
                 string nsUri = mgr.LookupNamespace(attr.LocalName);
                 if (nsUri != null)
                 {
                     if (attr.Value == nsUri)
                         elem.Attributes.RemoveNodeAt(i);
                 }
                 else
                 {
                     // Add this namespace, so it we will behave correctly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as
                     // InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>"
                     // If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for
                     // the subsequent InnerXml_set or setting an EntRef inside.
                     mgr.AddNamespace(attr.LocalName, attr.Value);
                 }
             }
             else if (attr.Prefix.Length == 0 && attr.LocalName == _doc.strXmlns)
             {
                 string nsUri = mgr.DefaultNamespace;
                 if (nsUri != null)
                 {
                     if (attr.Value == nsUri)
                         elem.Attributes.RemoveNodeAt(i);
                 }
                 else
                 {
                     // Add this namespace, so it we will behave correctly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as
                     // InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>"
                     // If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for
                     // the subsequent InnerXml_set or setting an EntRef inside.
                     mgr.AddNamespace(attr.LocalName, attr.Value);
                 }
             }
         }
     }
     //now recursively remove the duplicate attributes on the children
     XmlNode child = elem.FirstChild;
     while (child != null)
     {
         XmlElement childElem = child as XmlElement;
         if (childElem != null)
             RemoveDuplicateNamespace(childElem, mgr, true);
         child = child.NextSibling;
     }
     mgr.PopScope();
 }