Exemplo n.º 1
0
 /// <summary>
 /// Initializes an instance of the <see cref="XDeclaration"/> class
 /// from another <see cref="XDeclaration"/> object.
 /// </summary>
 /// <param name="other">
 /// The <see cref="XDeclaration"/> used to initialize this <see cref="XDeclaration"/> object.
 /// </param>
 public XDeclaration(XDeclaration other)
 {
     if (other == null) throw new ArgumentNullException("other");
     _version = other._version;
     _encoding = other._encoding;
     _standalone = other._standalone;
 }
Exemplo n.º 2
0
		/////////////////////////////////////////////////////////////////////////////
		private void GetDataSetCompleted(object sender, GetOleDbDataSetCompletedEventArgs e)
		{
			if (m_RequestCompleteHandler == null)
				return;

			if (e.Error != null || e.Cancelled == true)
			{
				string error = (e.Cancelled ? "Cancelled" : e.Error.Message);
				m_RequestCompleteHandler.Invoke(error, null);
				return;
			}

			try
			{
				XElement xmlElement = e.Result;
				XDeclaration xmlDeclaration = new XDeclaration("1.0", "UTF-8", "yes");
				XDocument xmlDoc = new XDocument(xmlDeclaration, xmlElement); // xmlDoc.Root.Name should be "Root" or null
				// Note that if there is no root, the XML document is empty
				if (xmlDoc.Root != null && xmlDoc.Root.Name == "Error")
				{
					string error = "Error accessing the web service\r\n\r\n" + xmlDoc.Root.Value;
					m_RequestCompleteHandler.Invoke(error, null);
					return;
				}

				m_RequestCompleteHandler.Invoke(xmlDoc, null);
			}
			catch (Exception ex)
			{
				m_RequestCompleteHandler.Invoke(ex.Message, null);
			}
		}
Exemplo n.º 3
0
 /// <summary>
 /// 创建一个新Xml文档,根据该文档创建一个XmlHelper对象
 /// </summary>
 /// <param name="version">文档描述的版本号</param>
 /// <param name="encoding">文档描述的编码</param>
 /// <param name="standalone">文档描述的standlone属性</param>
 /// <param name="rootName">根节点的名称</param>
 public XmlHelper(string version, string encoding, string standalone,string rootName)
 {
     this._doc = new XDocument();
     var declaration = new XDeclaration(version,encoding,standalone);
     this._doc.Declaration = declaration;
     this._doc.Add(new XElement(rootName)); 
 }
Exemplo n.º 4
0
 public XDocument(XDocument other) : base(other)
 {
     if (other.declaration != null)
     {
         this.declaration = new XDeclaration(other.declaration);
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// 创建一个新Xml文档,根据该文档创建一个XmlHelper对象
        /// </summary>
        /// <param name="version">文档描述的版本号</param>
        /// <param name="encoding">文档描述的编码</param>
        /// <param name="standalone">文档描述的standlone属性</param>
        /// <param name="rootName">根节点的名称</param>
        public XmlHelper(string version, string encoding, string standalone, string rootName)
        {
            this._doc = new XDocument();
            var declaration = new XDeclaration(version, encoding, standalone);

            this._doc.Declaration = declaration;
            this._doc.Add(new XElement(rootName));
        }
Exemplo n.º 6
0
 public XDeclaration(XDeclaration other)
 {
     if (other == null)
         throw new ArgumentNullException ("other");
     this.version = other.version;
     this.encoding = other.encoding;
     this.standalone = other.standalone;
 }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes an instance of the <see cref="XDeclaration"/> class
        /// from another <see cref="XDeclaration"/> object.
        /// </summary>
        /// <param name="other">
        /// The <see cref="XDeclaration"/> used to initialize this <see cref="XDeclaration"/> object.
        /// </param>
        public XDeclaration(XDeclaration other)
        {
            ArgumentNullException.ThrowIfNull(other);

            _version    = other._version;
            _encoding   = other._encoding;
            _standalone = other._standalone;
        }
Exemplo n.º 8
0
 /// <summary>
 /// Initializes an instance of the <see cref="XDeclaration"/> class
 /// from another <see cref="XDeclaration"/> object.
 /// </summary>
 /// <param name="other">
 /// The <see cref="XDeclaration"/> used to initialize this <see cref="XDeclaration"/> object.
 /// </param>
 public XDeclaration(XDeclaration other)
 {
     if (other == null)
     {
         throw new ArgumentNullException(nameof(other));
     }
     _version    = other._version;
     _encoding   = other._encoding;
     _standalone = other._standalone;
 }
Exemplo n.º 9
0
 int GetHashCode(XDeclaration d)
 {
     if (d == null)
     {
         return(0);
     }
     return((d.Version.GetHashCode() << 7) ^
            (d.Encoding.GetHashCode() << 6) ^
            d.Standalone.GetHashCode());
 }
Exemplo n.º 10
0
 /// <summary>
 /// Initializes an instance of the <see cref="XDeclaration"/> class
 /// from another <see cref="XDeclaration"/> object.
 /// </summary>
 /// <param name="other">
 /// The <see cref="XDeclaration"/> used to initialize this <see cref="XDeclaration"/> object.
 /// </param>
 public XDeclaration(XDeclaration other)
 {
     if (other == null)
     {
         throw new ArgumentNullException("other");
     }
     version    = other.version;
     encoding   = other.encoding;
     standalone = other.standalone;
 }
Exemplo n.º 11
0
        public static string GetXML()
        {
            var employees = GetEmployees();
            var declaration = new XDeclaration("1.0", "utf-8", "yes");
            var doc = new XDocument(declaration, employees);

            var writer = new StringWriter();
            doc.Save(writer);

            return writer.GetStringBuilder().ToString();
        }
Exemplo n.º 12
0
        public void CreateDocumentWithContent()
        {
            XDeclaration declaration = new XDeclaration("1.0", "utf-8", "yes");
            XComment comment = new XComment("This is a document");
            XProcessingInstruction instruction = new XProcessingInstruction("doc-target", "doc-data");
            XElement element = new XElement("RootElement");

            XDocument doc = new XDocument(declaration, comment, instruction, element);

            Assert.Equal(new XNode[] { comment, instruction, element }, doc.Nodes());
        }
Exemplo n.º 13
0
        public void WriteToFile ()
        {
            // Corrected header of the plist
            string publicId = "-//Apple//DTD PLIST 1.0//EN";
            string stringId = "http://www.apple.com/DTDs/PropertyList-1.0.dtd";
            string internalSubset = null;
            XDeclaration declaration = new XDeclaration ("1.0", Encoding.UTF8.EncodingName, null);
            XDocumentType docType = new XDocumentType ("plist", publicId, stringId, internalSubset);

            this.XMLDict.Save (this.filePath, declaration, docType);
        }
 public void WriteBookList(IEnumerable<Book> books)
 {
     XElement xBooks = new XElement("BookList",
         books.Select(book =>
         new XElement("Book",
             new XElement("Author", book.Author),
             new XElement("Title", book.Title),
             new XElement("Publisher", book.Publisher))));
     XDeclaration xDecl = new XDeclaration("1.0", "UTF-8", "no");
     XDocument xDoc = new XDocument(xDecl, xBooks);
     xDoc.Save(filePath);
 }
Exemplo n.º 15
0
                /// <summary>
                /// Validate behavior of the XDocument copy/clone constructor.
                /// </summary>
                /// <returns>true if pass, false if fail</returns>
                //[Variation(Desc = "CreateDocumentCopy")]
                public void CreateDocumentCopy()
                {
                    try
                    {
                        new XDocument((XDocument)null);
                        Validate.ExpectedThrow(typeof(ArgumentNullException));
                    }
                    catch (Exception ex)
                    {
                        Validate.Catch(ex, typeof(ArgumentNullException));
                    }

                    XDeclaration declaration = new XDeclaration("1.0", "utf-8", "yes");
                    XComment comment = new XComment("This is a document");
                    XProcessingInstruction instruction = new XProcessingInstruction("doc-target", "doc-data");
                    XElement element = new XElement("RootElement");

                    XDocument doc = new XDocument(declaration, comment, instruction, element);

                    XDocument doc2 = new XDocument(doc);

                    IEnumerator e = doc2.Nodes().GetEnumerator();

                    // First node: declaration
                    Validate.IsEqual(doc.Declaration.ToString(), doc2.Declaration.ToString());

                    // Next node: comment
                    Validate.IsEqual(e.MoveNext(), true);
                    Validate.Type(e.Current, typeof(XComment));
                    Validate.IsNotReferenceEqual(e.Current, comment);
                    XComment comment2 = (XComment)e.Current;
                    Validate.IsEqual(comment2.Value, comment.Value);

                    // Next node: processing instruction
                    Validate.IsEqual(e.MoveNext(), true);
                    Validate.Type(e.Current, typeof(XProcessingInstruction));
                    Validate.IsNotReferenceEqual(e.Current, instruction);
                    XProcessingInstruction instruction2 = (XProcessingInstruction)e.Current;
                    Validate.String(instruction2.Target, instruction.Target);
                    Validate.String(instruction2.Data, instruction.Data);

                    // Next node: element.
                    Validate.IsEqual(e.MoveNext(), true);
                    Validate.Type(e.Current, typeof(XElement));
                    Validate.IsNotReferenceEqual(e.Current, element);
                    XElement element2 = (XElement)e.Current;
                    Validate.ElementName(element2, element.Name.ToString());
                    Validate.Count(element2.Nodes(), 0);

                    // Should be end.
                    Validate.IsEqual(e.MoveNext(), false);
                }
        public XDocument CompileDocument(ConnectionInfo serializationTarget, bool fullFileEncryption, bool export)
        {
            var rootNodeInfo = GetRootNodeFromConnectionInfo(serializationTarget);
            _encryptionKey = rootNodeInfo.PasswordString.ConvertToSecureString();
            var rootElement = CompileRootNode(rootNodeInfo, fullFileEncryption, export);

            CompileRecursive(serializationTarget, rootElement);
            var xmlDeclaration = new XDeclaration("1.0", "utf-8", null);
            var xmlDocument = new XDocument(xmlDeclaration, rootElement);
            if (fullFileEncryption)
                xmlDocument = new XmlConnectionsDocumentEncryptor(_cryptographyProvider).EncryptDocument(xmlDocument, _encryptionKey);
            return xmlDocument;
        }
Exemplo n.º 17
0
 public static void InitDebils()
 {
     XDocument Debili = new XDocument();
       XDeclaration Xdec = new XDeclaration("1.0", "utf-8", "yes");
       XComment Com = new XComment("Не изменяйте нижнюю строчку");
       XElement Stud =  new XElement("StudList",
       new XElement("Class", new XAttribute("ID", 1),
     new XElement("Name", "Витек Мартынов"),
     new XElement("Name", "Батруха Иисусов"),
     new XElement("Name", "Шланг Волосатый")));
       //Debili.Add(Xdec);
       Debili.Add(Stud);
       Debili.Save("Test.xml");
 }
Exemplo n.º 18
0
 public CortanaXmlGenerator(string prefix,string example)
 {
     doc = new XDocument();
     XDeclaration dec = new XDeclaration("1.0", "utf-8", "no");
     doc.Declaration = dec;
     XElement root = new XElement("VoiceCommands");
     root.SetAttributeValue("def", "defVal");
     doc.Add(root);
     commandSet = new XElement("CommandSet");
     commandSet.SetAttributeValue("xmllang", "ja-JP");
     commandSet.Add(new XElement("CommandPrefix", prefix));
     commandSet.Add(new XElement("Example", example));
     root.Add(commandSet);
 }
Exemplo n.º 19
0
 bool Equals(XDeclaration d1, XDeclaration d2)
 {
     if (d1 == null)
     {
         return(d2 == null);
     }
     else if (d2 == null)
     {
         return(false);
     }
     return(d1.Version == d2.Version &&
            d1.Encoding == d2.Encoding &&
            d1.Standalone == d2.Standalone);
 }
Exemplo n.º 20
0
        object GetName(int attr)
        {
            if (attr >= 0)
            {
                switch (node.NodeType)
                {
                case XmlNodeType.Element:
                    XAttribute a = GetXAttribute(attr);
                    return(a.Name);

                case XmlNodeType.DocumentType:
                    if (attr == 0)
                    {
                        return(((XDocumentType)node).PublicId != null ? "PUBLIC" : "SYSTEM");
                    }
                    return("SYSTEM");

                case XmlNodeType.Document:
                    XDeclaration xd = ((XDocument)node).Declaration;
                    switch (attr)
                    {
                    case 0:
                        return(xd.Version != null ? "version" : xd.Encoding != null ? "encoding" : "standalone");

                    case 1:
                        return(xd.Version != null ? (xd.Encoding != null ? "encoding" : "standalone") : "standalone");
                    }
                    return("standalone");
                }
            }
            else
            {
                switch (node.NodeType)
                {
                case XmlNodeType.Document:
                    return("xml");                    // xmldecl

                case XmlNodeType.Element:
                    return(((XElement)node).Name);

                case XmlNodeType.ProcessingInstruction:
                    return(((XPI)node).Target);

                case XmlNodeType.DocumentType:
                    return(((XDocumentType)node).Name);
                }
            }
            return(null);
        }
Exemplo n.º 21
0
 public static XDeclaration SetDeclaration(this XDocument doc, string version = "1.0", string encoding = "utf-8", string standalone = null)
 {
     if (doc.Declaration != null)
     {
         doc.Declaration.Version    = version;
         doc.Declaration.Encoding   = encoding;
         doc.Declaration.Standalone = standalone;
     }
     else
     {
         XDeclaration declaration = new XDeclaration(version, encoding, standalone);
         doc.Declaration = declaration;
     }
     return(doc.Declaration);
 }
Exemplo n.º 22
0
        private static bool EqualDeclarations(XDeclaration expected, XDeclaration actual)
        {
            if (expected == null && actual == null)
            {
                return true;
            }

            if (expected == null || actual == null)
            {
                return false;
            }

            // Note that this ignores 'Standalone' property comparison.
            return string.Equals(expected.Version, actual.Version, StringComparison.OrdinalIgnoreCase)
                && string.Equals(expected.Encoding, actual.Encoding, StringComparison.OrdinalIgnoreCase);
        }
Exemplo n.º 23
0
        /// <summary>
        /// create a new ship's data file
        /// </summary>
        /// <param name="shipname"></param>
        /// <param name="man"></param>
        /// <param name="power"></param>
        /// <param name="jump"></param>
        /// <param name="power"></param>
        /// <param name="cargo">int - cargo capacity in Dtons</param>
        /// <param name="credits">int - current credits</param>
        /// <param name="day">int - day (0..365)</param>
        /// <param name="jumpcost">int - cost per jump (fuel, life support, etc)</param>
        /// <param name="monthly">int - monthly costs (mortgage, maintenance, etc)</param>
        /// <param name="sec">string - SEC string of initial system</param>
        /// <param name="version">string - version: CT, MT, T5, CU</param>
        /// <param name="year">int - imperial year (i.e., 1105)</param>
        /// <param name="secfile">string - SEC format file</param>
        public Starship(string shipname, int man, int power, int jump, int cargo, int monthly, int jumpcost, int day, int year, 
            int credits, string version, string secfile, string sec, string sectorname, int tradeDM, bool illegals)
        {
            XDocument ns = new XDocument();
            XDeclaration dec = new XDeclaration("1.0", "utf-8", "yes");
            ns.AddAnnotation(dec);

            XElement rootNode = new XElement("ShipData");
            ns.Add(rootNode);

            ns.Element("ShipData").Add(
                new XElement("system",
                    new XAttribute("version", version),
                    new XElement("day", day.ToString()),
                    new XElement("year", year.ToString()),
                    new XElement("sec", sec),
                    new XElement("secfile", secfile),
                    new XElement("sectorName", sectorname),
                    new XElement("cargoID",0),
                    new XElement("tradeDM", tradeDM),
                    new XElement("illegals", illegals)));

            ns.Element("ShipData").Add(
                new XElement("Ship"));

            ns.Element("ShipData").Element("Ship").Add(
                    new XElement("Name", shipname),
                    new XElement("Manuever", man.ToString()),
                    new XElement("Power", power.ToString()),
                    new XElement("Jump", jump.ToString()),
                    new XElement("Cargo", cargo.ToString()),
                    new XElement("CargoHeld", "0"),
                    new XElement("credits", credits),
                    new XElement("costs",
                        new XElement("Monthly", monthly.ToString()),
                        new XElement("perJump", jumpcost.ToString()),
                        new XElement("lastPaid", String.Format("{0:000}-{1:0000}", day, year))));

            ns.Element("ShipData").Add(
                new XElement("Cargo"));
            ns.Element("ShipData").Add(
                new XElement("Travelogue"));

            ns.Save(shipname + ".xml");

            clearData();
        }
Exemplo n.º 24
0
        public void CreateDocumentCopy()
        {
            Assert.Throws<ArgumentNullException>(() => new XDocument((XDocument)null));

            XDeclaration declaration = new XDeclaration("1.0", "utf-8", "yes");
            XComment comment = new XComment("This is a document");
            XProcessingInstruction instruction = new XProcessingInstruction("doc-target", "doc-data");
            XElement element = new XElement("RootElement");

            XDocument doc = new XDocument(declaration, comment, instruction, element);

            XDocument doc2 = new XDocument(doc);

            IEnumerator e = doc2.Nodes().GetEnumerator();

            // First node: declaration
            Assert.Equal(doc.Declaration.ToString(), doc2.Declaration.ToString());

            // Next node: comment
            Assert.True(e.MoveNext());
            Assert.IsType<XComment>(e.Current);
            Assert.NotSame(comment, e.Current);

            XComment comment2 = (XComment)e.Current;
            Assert.Equal(comment.Value, comment2.Value);

            // Next node: processing instruction
            Assert.True(e.MoveNext());
            Assert.IsType<XProcessingInstruction>(e.Current);
            Assert.NotSame(instruction, e.Current);

            XProcessingInstruction instruction2 = (XProcessingInstruction)e.Current;
            Assert.Equal(instruction.Target, instruction2.Target);
            Assert.Equal(instruction.Data, instruction2.Data);

            // Next node: element.
            Assert.True(e.MoveNext());
            Assert.IsType<XElement>(e.Current);
            Assert.NotSame(element, e.Current);

            XElement element2 = (XElement)e.Current;
            Assert.Equal(element.Name.ToString(), element2.Name.ToString());
            Assert.Empty(element2.Nodes());

            // Should be end.
            Assert.False(e.MoveNext());
        }
Exemplo n.º 25
0
		public void TestDefaultXmlFormatter()
		{
			var sut = _xmlFormatter;

			XDeclaration declaration = new XDeclaration("1.0", "UTF-8", null);
			XElement content = new XElement("root", new XElement("person", 1));
			XDocument document = new XDocument(declaration, content);

			string xmlString = sut.Format(document);

			string expected =
@"<?xml version=""1.0"" encoding=""utf-8""?>
<root>
  <person>1</person>
</root>";
			Assert.Equal(expected, xmlString);
		}
Exemplo n.º 26
0
        public static XDocument ConvertOpcToFlat(Stream myStream)
        {
            using (Package package = Package.Open(myStream))
            {
                XNamespace pkg = "http://schemas.microsoft.com/office/2006/xmlPackage";

                XDeclaration declaration = new XDeclaration("1.0", "UTF-8", "yes");

                XDocument doc = new XDocument(
                    declaration,
                    new XProcessingInstruction("mso-application", "progid=\"Word.Document\""),
                    new XElement(pkg + "package", new XAttribute(XNamespace.Xmlns + "pkg", pkg.ToString()),
                        package.GetParts().Select(part => GetContentsAsXml(part))
                    )
                );
                return doc;
            }
        }
Exemplo n.º 27
0
        public XDocument GetXspf(IEnumerable<Track> tracks)
        {
            var xmlDeclaration = new XDeclaration("1.0", "utf-8", "no");
            XNamespace xspfNamespace = "http://xspf.org/ns/0/";
            var xmlDoc = new XDocument(xmlDeclaration);

            var root = new XElement
                (xspfNamespace + "playlist",
                    new XElement("title", "Opentape"),
                    new XElement("annotation", "Songs, "),
                    new XElement("creator", "Songs, "),
                    new XElement("location", "Songs, "),
                    new XElement("info", "Songs, "),
                    new XElement("tracklist", "Songs, "),
                    GetTracks(tracks)
                );

            return xmlDoc;
        }
Exemplo n.º 28
0
        public ModConfig(MinecraftPaths p)
        {
            paths = p;

            if (!File.Exists(Path.Combine(p.appConfigDir, "config.xml")))
            {
                XDeclaration dec = new XDeclaration("1.0", "UTF-8", "yes");
                document = new XDocument();
                document.Declaration = dec;
                document.Add(new XElement("SMMMconfig"));
                document.Save(Path.Combine(paths.appConfigDir, "config.xml"));
            }
            else
            {
                document = XDocument.Load(Path.Combine(p.appConfigDir, "config.xml"));
            }
            m_numMods = document.Elements().ElementAt(0).Elements().Count();
            OnConfigChanged(EventArgs.Empty);
        }
Exemplo n.º 29
0
 void ReadContent(XmlReader reader, LoadOptions options)
 {
     if (reader.ReadState == ReadState.Initial)
     {
         reader.Read();
     }
     if (reader.NodeType == XmlNodeType.XmlDeclaration)
     {
         Declaration = new XDeclaration(
             reader.GetAttribute("version"),
             reader.GetAttribute("encoding"),
             reader.GetAttribute("standalone"));
         reader.Read();
     }
     ReadContentFrom(reader, options);
     if (Root == null)
     {
         throw new InvalidOperationException("The document element is missing.");
     }
 }
Exemplo n.º 30
0
        //Create declaration
        public void BuildXMLDoc(string[] filename, BitmapFrame[] frames, int width, int height, Vector[] xy)
        {
            XDeclaration XMLdec = new XDeclaration("1.0", "UTF-8", "yes");
            //fill with frames
            Object[] XMLelem = new Object[frames.Length];
            for (int i = 0; i < frames.Length; i++)
            {
                XElement node = new XElement("SubTexture");

                BitmapFrame eek = frames[i];

                node.SetAttributeValue("name", filename[i]);
                node.SetAttributeValue("x", xy[i].X);
                node.SetAttributeValue("y", xy[i].Y);
                node.SetAttributeValue("width", frames[i].PixelWidth);
                node.SetAttributeValue("height", frames[i].PixelHeight);

                XMLelem[i] = node;

            }
            XElement XMLRootNode = new XElement("TextureAtlas", XMLelem);
            XMLRootNode.SetAttributeValue("imagePath", "Naw");

            XDocument XMLdoc = new XDocument(XMLdec, XMLRootNode);

            AtlasXML = XMLdoc;

            Microsoft.Win32.SaveFileDialog saveDiag = new Microsoft.Win32.SaveFileDialog();
            Nullable<bool> diagResult = saveDiag.ShowDialog();

            if (diagResult == true)
            {
                FileStream XMLstream = new FileStream(saveDiag.FileName, FileMode.Create);
                XMLdoc.Save(XMLstream);
                XMLstream.Close();
            }
            else
            {
                return;
            }
        }
Exemplo n.º 31
0
 public string ToKml()
 {
     var declaration = new XDeclaration("1.0", "utf-8","yes");
     var document = new XDocument(declaration);
     var kml = new XElement("kml");
     kml.Add(new XAttribute("prefix","http://www.opengis.net/kml/2.2"));
     var element = new XElement("Document");
     foreach(var style in Symbols)
     {
         element.Add(style.ToKml());
     }
     foreach (var feature in Features)
     {
         element.Add(feature.ToKml());
     }
     kml.Add(element);
     document.Add(kml);
     var result = string.Concat(document.Declaration.ToString(), document.ToString());
     result = result.Replace("prefix", "xmlns");
     result = result.Replace(" standalone=\"yes\"", string.Empty);
     return result;
 }
        /// <summary>
        /// Creates a new instance of TableStorageRequestBody
        /// </summary>
        public TableStorageRequestBody()
        {
            Declaration = new XDeclaration("1.0", "utf-8", "yes");

            Add(
                new XElement(StorageHttpConstants.Namespaces.Atom + "entry",
                    new XAttribute("xmlns", StorageHttpConstants.Namespaces.Atom),
                    new XAttribute(XNamespace.Xmlns + "d", StorageHttpConstants.Namespaces.DataServices),
                    new XAttribute(XNamespace.Xmlns + "m", StorageHttpConstants.Namespaces.MetaData),

                    new XElement(StorageHttpConstants.Namespaces.Atom + "title"),
                    new XElement(StorageHttpConstants.Namespaces.Atom + "updated", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ", CultureInfo.InvariantCulture)),
                    new XElement(StorageHttpConstants.Namespaces.Atom + "author",
                        new XElement(StorageHttpConstants.Namespaces.Atom + "name")
                    ),
                    new XElement(StorageHttpConstants.Namespaces.Atom + "id"),

                    new XElement(StorageHttpConstants.Namespaces.Atom + "content",
                        new XAttribute("type", "application/xml"),
                        new XElement(StorageHttpConstants.Namespaces.MetaData + "properties")
                    )
                )
            );
        }
Exemplo n.º 33
0
        static void Main(string[] args)
        {
            XDocument document = new XDocument();
            //第三个参数为yes,说明这个xml是单纯的xml无任何规定,能随意写标签
            XDeclaration delaration = new XDeclaration("1.0", "utf-8", "yes");
            //文档声明写入文档
            document.Declaration = delaration;

            //XElement rootNode = new XElement("根节点", "这是根节点的内容,但是一般不放文字");
            XElement rootNode = new XElement("根节点");

            //在根节点内加入两个有内容的子节点
            XElement sonNode1 = new XElement("子节点1", "我是有文字内容的");
            rootNode.Add(sonNode1);
            XElement sonNode2 = new XElement("子节点2", "我是有文字内容的");
            rootNode.Add(sonNode2);

            //加入有子节点的子节点
            XElement sonNode3 = new XElement("子节点3");
            //这个节点加入子节点
            XElement sunNode1 = new XElement("孙节点", "我有文字内容和属性");
            //给这个节点设置属性
            sunNode1.SetAttributeValue("id", "孙节点1好");
            sonNode3.Add(sunNode1);
            rootNode.Add(sonNode3);

            //直接在根节点添加子节点,但是这样拿不到子节点对象
            rootNode.SetElementValue("子节点4", "我有文字内容");
            //设置属性
            rootNode.SetAttributeValue("id", "唯一的根节点");

            document.Add(rootNode);
            document.Save("xml文档.xml");
            Console.WriteLine("ok");
            Console.ReadKey();
        }
Exemplo n.º 34
0
 public XDeclarationWrapper(XDeclaration declaration)
   : base(null)
 {
   Declaration = declaration;
 }
Exemplo n.º 35
0
 /// <summary>
 /// Creates an empty user.config file...looks like the one MS creates.  
 /// This could be overkill a simple key/value pairing would probably do.
 /// </summary>
 private void CreateEmptyConfig()
 {
     var doc = new XDocument();
     var declaration = new XDeclaration("1.0", "utf-8", "true");
     var config = new XElement(CONFIG);
     var userSettings = new XElement(USER_SETTINGS);
     var group = new XElement(typeof(Properties.Settings).FullName);
     userSettings.Add(group);
     config.Add(userSettings);
     doc.Add(config);
     doc.Declaration = declaration;
     doc.Save(UserConfigPath);
 }
Exemplo n.º 36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XDocument"/> class
 /// with the specified <see cref="XDeclaration"/> and content.
 /// </summary>
 /// <param name="declaration">
 /// The XML declaration for the document.
 /// </param>
 /// <param name="content">
 /// The contents of the document.
 /// </param>
 /// <remarks>
 /// Valid content includes:
 /// <list>
 /// <item>Zero or one <see cref="XDocumentType"/> objects</item>
 /// <item>Zero or one elements</item>
 /// <item>Zero or more comments</item>
 /// <item>Zero or more processing instructions</item>
 /// <item></item>
 /// </list>
 /// See XContainer.Add(object content) for details about the content that can be added
 /// using this method.
 /// </remarks>
 public XDocument(XDeclaration declaration, params object[] content)
     : this(content)
 {
     this.declaration = declaration;
 }
Exemplo n.º 37
0
 /// <summary>
 /// Invoked for each <see cref="XDeclaration"/>
 /// </summary>
 /// <param name="declaration"></param>
 public virtual void Visit(XDeclaration declaration)
 {
     Contract.Requires<ArgumentNullException>(declaration != null);
 }
Exemplo n.º 38
0
 /// <summary>
 /// Initializes an instance of the <see cref="XDeclaration"/> class
 /// from another <see cref="XDeclaration"/> object.
 /// </summary>
 /// <param name="other">
 /// The <see cref="XDeclaration"/> used to initialize this <see cref="XDeclaration"/> object.
 /// </param>
 public XDeclaration(XDeclaration other !!)
 {
Exemplo n.º 39
0
 public XDocument(XDeclaration declaration, params object [] content)
 {
     Declaration = declaration;
     Add(content);
 }
Exemplo n.º 40
0
                /// <summary>
                /// Validate behavior of the XDocument XmlDeclaration property.
                /// </summary>
                /// <returns>true if pass, false if fail</returns>
                //[Variation(Desc = "DocumentXmlDeclaration")]
                public void DocumentXmlDeclaration()
                {
                    XDocument doc = new XDocument();
                    Validate.IsNull(doc.Declaration);

                    XDeclaration dec = new XDeclaration("1.0", "utf-16", "yes");
                    XDocument doc2 = new XDocument(dec);
                    XDeclaration dec2 = doc2.Declaration;
                    Validate.IsReferenceEqual(dec2, dec);

                    doc2.RemoveNodes();
                    Validate.IsNotNull(doc2.Declaration);
                }
Exemplo n.º 41
0
 public XDocument(XDeclaration xmldecl, params object [] content)
 {
     Declaration = xmldecl;
     Add(content);
 }
 // Summary:
 //     Initializes a new instance of the System.Xml.Linq.XDeclaration class from
 //     another System.Xml.Linq.XDeclaration object.
 //
 // Parameters:
 //   other:
 //     The System.Xml.Linq.XDeclaration used to initialize this System.Xml.Linq.XDeclaration
 //     object.
 public XDeclaration(XDeclaration other)
 {
     Contract.Requires(other != null);
 }
Exemplo n.º 43
0
 //
 // Summary:
 //     Initializes a new instance of the System.Xml.Linq.XDocument class with the
 //     specified System.Xml.Linq.XDeclaration and content.
 //
 // Parameters:
 //   declaration:
 //     An System.Xml.Linq.XDeclaration for the document.
 //
 //   content:
 //     The content of the document.
 extern public XDocument(XDeclaration declaration, params object[] content);
        private void CheckOrCreateInstanceFiles()
        {
            // Is there at least on instance file?

            // Is each instance file syntactically correct? If not, delete it.

            int validInstances = 0;

            foreach (string fname in Directory.GetFiles(settingsDirectory))
            {
                if(fname.Contains(instanceFilenamePrefix))
                {
                    XDocument potentialInstance = XDocument.Load(fname);
                    // Verify it contains the root instance element
                    if (potentialInstance.Elements(rootElementName_Instance).Any())
                    {
                        // The file structure is good.
                        EventLogger.LogMessage("Instance file " + fname + " found and verified.", TraceLevel.Info);
                        validInstances++;
                    }
                    else
                    {
                        // The file is does not contain the correct root element. Delete it
                        EventLogger.LogMessage("Invalid Instance file " + fname + " found and Deleted.", TraceLevel.Warning);
                        File.Delete(fname);
                    }

                }
            }

            // If no instances exist, create one.
            if (validInstances < 1)
            {
                // Create the first (default) instance and set it as the current instance
                EventLogger.LogMessage("Creating new Instance XML Settings File", TraceLevel.Info);
                XDeclaration dec = new XDeclaration("1.0", "UTF-8", "yes");
                XElement rootElement = new XElement(rootElementName_Instance);
                rootElement.SetAttributeValue("Name", productName);
                XDocument newInstanceDoc = new XDocument(dec, rootElement);
                currentInstanceFilename = settingsDirectory + instanceFilenamePrefix + getNewInstanceFilenameSuffix();
                newInstanceDoc.Save(currentInstanceFilename);
                CurrentInstance = productName;
                DefaultInstance = productName;
            }
            else
            {
                // Verify that the default instance exists.
                List<string> instances = getListOfInstances();

                if (!instances.Contains(DefaultInstance))
                    DefaultInstance = instances[0];

                // The default instance is set and verified, now set the current instance

                // Try the default instance first...
                string defInst = DefaultInstance;
                if (!CheckIfInstanceIsInUse(defInst))
                {
                    CurrentInstance = defInst;
                }
                else
                {
                    // Check for other unused instances, and use the first one available...
                    bool instanceFound = false;
                    foreach (string name in instances)
                    {
                        if (!CheckIfInstanceIsInUse(name))
                        {
                            CurrentInstance = name;
                            instanceFound = true;
                            break;
                        }
                    }

                    if (!instanceFound)// Create a new instance to use
                    {
                        // Determine the new name
                        int i = 1;
                        string autoName =  productName + "(Auto-Created " + i.ToString() + ")";
                        while(instances.Contains(autoName))
                        {
                            i++;
                            autoName =  productName + "(Auto-Created " + i.ToString() + ")";
                        }
                        // Name is unique. Create the new instance.
                        CreateNewInstance(autoName);
                        CurrentInstance = autoName;
                    }
                }
            }
        }
        public static string[] OpcToText(string fileName)
        {
            using (Package package = Package.Open(fileName))
            {
                XNamespace pkg = "http://schemas.microsoft.com/office/2006/xmlPackage";

                XDeclaration declaration = new XDeclaration("1.0", "UTF-8", "yes");
                XDocument doc = new XDocument(
                    declaration,
                    GetProcessingInstruction(fileName),
                    new XElement(pkg + "package",
                        new XAttribute(XNamespace.Xmlns + "pkg", pkg.ToString()),
                        package.GetParts().Select(part => GetContentsAsXml(part))
                    )
                );
                return doc.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            }
        }
Exemplo n.º 46
0
        //保存
        private void SaveTOXml()
        {
            XDeclaration dec = new XDeclaration("1.0", "utf-8", "yes");
            XDocument xml = new XDocument(dec);

            XElement root = new XElement("Tree");

            foreach (TreeNode node in treeView1.Nodes)
            {
                XElement e = CreateElements(node);
                root.Add(e);
            }
            xml.Add(root);
            xml.Save(mf.DirXml + @"\Nav.xml");
        }