コード例 #1
0
    protected void uploadMiasta_Click(object sender, EventArgs e)
    {
        if(fileMiasta.HasFile)
        {
            MemoryStream stream = new MemoryStream(fileMiasta.FileBytes);
            XmlReaderSettings settings = new XmlReaderSettings();

            int i = 0;
            Repository<City, Guid> cityrep = new Repository<City, Guid>();
            using (XmlReader r = XmlReader.Create(stream, settings))
            {
                XPathDocument xpathDoc = new XPathDocument(r);
                XPathNavigator xpathNav = xpathDoc.CreateNavigator();

                string xpathQuery = "/teryt/catalog/row/col[attribute::name='NAZWA']";

                XPathExpression xpathExpr = xpathNav.Compile(xpathQuery);

                XPathNodeIterator xpathIter = xpathNav.Select(xpathExpr);

                while (xpathIter.MoveNext())
                {
                    City city = new City();
                    city.Name = xpathIter.Current.Value;

                    cityrep.SaveOrUpdate(city);
                    if (i % 500 == 0)
                        HBManager.Instance.GetSession().Flush();
                    i++;
                    //AddressManager.InsertCity(new City { Name = xpathIter.Current.Value });
                }
            }
            HBManager.Instance.GetSession().Flush();
        }
    }
コード例 #2
0
    private void Images()
    {
         // Dataset containing 
        string catname ="Electricals";
        ProductImageService.serProdctImage prodimage = new ProductImageService.serProdctImage();
        DataSet dataset = prodimage.ProductImage_GetFashImgtwoForHandler(catname);
        //string x = dataset.GetXml();
        string xmlfile = dataset.GetXml();

        XslTransform xslt = new XslTransform();
        xslt.Load(Server.MapPath("~/xslt/HomeXSLTFile.xslt"));
        XPathDocument xpathdocument = new
        XPathDocument(xmlfile);
        XmlTextWriter writer = new XmlTextWriter(Console.Out);
        writer.Formatting = Formatting.Indented;

        xslt.Transform(xpathdocument, null, writer, null);
        


        //strstudentDetails = GetHtml(Server.MapPath("~/xsl/studentDetails.xsl"), strXML);

        //XPathDocument myXPathDoc = new XPathDocument(myXmlFile);
        //XslCompiledTransform myXslTrans = new XslCompiledTransform();
        //myXslTrans.Load(myStyleSheet);
        //XmlTextWriter myWriter = new XmlTextWriter("result.html", null);
        //myXslTrans.Transform(myXPathDoc, null, myWriter);
     }
コード例 #3
0
    /// <summary>
    /// Gets the time zone.
    /// </summary>
    /// <param name="offset">The offset.</param>
    /// <returns></returns>
    private static string GetTimeZone(double offset)
    {
        //Adjust result based on the server time zone
        string timeZoneKey = "timeOffset" + offset.ToString("F");
        string result = (CallContext.GetData(timeZoneKey) ?? "").ToString();
        if (result.Length == 0)
        {
            string zonesDocPath = HttpRuntime.AppDomainAppPath +"app_data/TimeZones.xml";
            XPathDocument timeZonesDoc = new XPathDocument(zonesDocPath);
            try
            {
                string xPath = "/root/option[@value='" + offset.ToString("F") + "']";
                XPathNavigator searchNavigator = timeZonesDoc.CreateNavigator();
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(searchNavigator.NameTable);
                XPathNodeIterator iterator = searchNavigator.Select(xPath, nsmgr);
                if (iterator.MoveNext())
                {
                    result = iterator.Current.Value;
                    if (!string.IsNullOrEmpty(result))
                    {
                        CallContext.SetData(timeZoneKey, result);
                    }
                }

            }
            catch (Exception ex)
            {
                return  ex.Message;
            }
        }

        return result;
    }
コード例 #4
0
    protected override void OnInit(EventArgs e)
    {
        string filename = Server.MapPath("settings.xml");
        XPathDocument document = new XPathDocument(filename);
        XPathNavigator navigator = document.CreateNavigator();
        XPathExpression expression = navigator.Compile("/appSettings/*");
        XPathNodeIterator iterator = navigator.Select(expression);

        HtmlTable table = new HtmlTable();
        HtmlTableRow row = new HtmlTableRow();
        HtmlTableCell cell = new HtmlTableCell();
        string tooltip = "";
        try
        {
            while (iterator.MoveNext())
            {
                tooltip = "";
                row = new HtmlTableRow();
                cell = new HtmlTableCell();

                XPathNavigator navigator2 = iterator.Current.Clone();
                Label label = new Label();
                label.ID = navigator2.Name + "Label";
                label.Text = navigator2.GetAttribute("name", navigator2.NamespaceURI);
                tooltip = navigator2.GetAttribute("description", navigator2.NamespaceURI);

                Control c = null;

                if (label.ID != "")
                {
                    c = new TextBox();
                    c.ID = navigator2.GetAttribute("name", navigator2.NamespaceURI) + "Textbox";
                    (c as TextBox).Text = navigator2.Value;
                    (c as TextBox).ToolTip = tooltip;
                    (c as TextBox).Width = 700;
                    (c as TextBox).TextMode = TextBoxMode.MultiLine;
                    label.ToolTip = tooltip;
                }

                cell.Controls.Add(label);
                row.Cells.Add(cell);

                cell = new HtmlTableCell();
                cell.Controls.Add(c);
                row.Cells.Add(cell);
                controls.Add(new ControlListItem(navigator2.Name, c.ID));

                table.Rows.Add(row);
            }
        }
        catch (Exception ex)
        {
            FormMessage.ForeColor = Color.Red;
            FormMessage.Text = ex.Message;
        }

        ControlsPanel.Controls.Add(table);

        base.OnInit(e);
    }
コード例 #5
0
ファイル: XmlToHtml.aspx.cs プロジェクト: Helen1987/edu
    protected void Page_Load(object sender, EventArgs e)
    {
		string xslFile = Server.MapPath("DvdList.xsl");
		string xmlFile = Server.MapPath("DvdList.xml");
		string htmlFile = Server.MapPath("DvdList.htm");

		XslTransform transf = new XslTransform();
		transf.Load(xslFile);
		transf.Transform(xmlFile, htmlFile);

		// Create an XPathDocument.
		XPathDocument xdoc = new XPathDocument(new XmlTextReader(xmlFile));

		// Create an XPathNavigator.

		XPathNavigator xnav = xdoc.CreateNavigator();

		// Transform the XML
		XmlReader reader = transf.Transform(xnav, null);

		// Go the the content and write it.
		reader.MoveToContent();
		Response.Write(reader.ReadOuterXml());
		reader.Close();
    }
コード例 #6
0
    public void Action() {   
        string xml = "<?xml version=\"1.0\"?>\n<a><b c=\"d\">e</b></a>";
        string xsl = "<?xml version=\"1.0\"?>\n" +
            "<xsl:stylesheet version=\"1.0\" " +
                    "xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" " +
                    "xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\" " +
                    "xmlns:js=\"urn:js\" " +
                ">" +
                "<msxsl:script language=\"jsCrIpt\" implements-prefix=\"js\">" +
                    "function SimpleTest() { return \"JScript test\"; }" +        
                "</msxsl:script>" +                
                "<xsl:template match=\"a\"><foo><xsl:apply-templates/></foo></xsl:template>" +
                "<xsl:template match=\"b\"><xsl:element name=\"bar\">" +
        	        "<xsl:attribute name=\"simpleTest\"><xsl:value-of select=\"js:SimpleTest()\"/></xsl:attribute>" +
                "</xsl:element></xsl:template>" +
                "<xsl:template match=\"/\"><xsl:apply-templates/></xsl:template>" +
            "</xsl:stylesheet>";            
    
        XPathDocument myXPathDocument = new XPathDocument(new XmlTextReader(new StringReader(xml)));

        XslTransform myXslTransform = new XslTransform();
        myXslTransform.Load(new XmlTextReader(new StringReader(xsl)));
        
        StringWriter myStringWriter = new StringWriter();
        XmlTextWriter myXmlWriter = new XmlTextWriter(myStringWriter);
        myXmlWriter.Formatting = Formatting.Indented;
        
        myXslTransform.Transform(myXPathDocument, null, myXmlWriter);
        myXmlWriter.Close();        
        
        Console.WriteLine(myStringWriter.ToString());
    }
コード例 #7
0
        private XPathNavigator SerializeAndReadOutput(ContentItem item)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            CreateExporter().Export(item, ExportOptions.Default, sw);

            StringReader   sr        = new StringReader(sb.ToString());
            XPathNavigator navigator = new XPathDocument(sr).CreateNavigator();

            navigator.MoveToFirstChild();
            return(navigator);
        }
コード例 #8
0
        private string TransformElements(string source)
        {
            XPathDocument doc = new XPathDocument(
                new StringReader("<root>" + source + "</root>"));
            XslTransform tr = new XslTransform();

            tr.Load("wiki2ecmahelper.xsl");
            XmlReader reader = tr.Transform(doc, null, (XmlResolver)null);

            reader.Read(); // should consume <root> start tag

            return(reader.ReadInnerXml());
        }
コード例 #9
0
ファイル: ExtensionsTest2.cs プロジェクト: fragmental/mono
        public void XPathDocumentMoveToId()
        {
            string         dtd = "<!DOCTYPE root [<!ELEMENT root EMPTY><!ATTLIST root id ID #REQUIRED>]>";
            string         xml = dtd + "<root id='aaa'/>";
            XPathNavigator nav = navigator = XDocument.Parse(xml).CreateNavigator();

            Assert.IsTrue(nav.MoveToId("aaa"), "ctor() from TextReader");

            XmlValidatingReader xvr = new XmlValidatingReader(xml, XmlNodeType.Document, null);

            nav = new XPathDocument(xvr).CreateNavigator();
            nav.MoveToId("aaa");              // it does not support this method
        }
        /// <summary>
        /// Initializes the syndication extension using the supplied <see cref="XmlReader"/> and <see cref="SyndicationResourceLoadSettings"/>.
        /// </summary>
        /// <param name="reader">The <b>XmlReader</b> used to load this <see cref="AtomPublishingControlSyndicationExtension"/>.</param>
        /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> used to configure the load operation.</param>
        /// <returns><b>true</b> if the <see cref="AtomPublishingControlSyndicationExtension"/> was able to be initialized using the supplied <paramref name="reader"/>; otherwise <b>false</b>.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="reader"/> is a null reference (Nothing in Visual Basic).</exception>
        public bool Load(XmlReader reader, SyndicationResourceLoadSettings settings)
        {
            Guard.ArgumentNotNull(reader, "reader");

            if (settings == null)
            {
                settings = new SyndicationResourceLoadSettings();
            }

            XPathDocument document = new XPathDocument(reader);

            return(this.Load(document.CreateNavigator(), settings));
        }
コード例 #11
0
ファイル: CursorXML.cs プロジェクト: sxkote/ReportGrabber
 public SXCursorXML(MemoryStream memory)
 {
     try
     {
         this.document = new XPathDocument(memory);
     }
     catch
     {
         this.document = null;
         this.Manager = null;
         this.Iterator = null;
     }
 }
コード例 #12
0
ファイル: Default.aspx.cs プロジェクト: kacecode/SchoolWork
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/xml";

        string xsltFile = Server.MapPath("books.xslt");
        string xmlFile = Server.MapPath("books.xml");

        XslCompiledTransform xslt = new XslCompiledTransform(true); //Pass in true to enable XSLT Debugging
        xslt.Load(xsltFile);

        XPathDocument doc = new XPathDocument(xmlFile);
        xslt.Transform(doc, new XmlTextWriter(Response.Output));
    }
コード例 #13
0
 /// <summary>
 /// 获取XML 节点的值
 /// </summary>
 /// <param name="path">创建只读的Xml类</param>
 /// <param name="selectNode">XML选择的节点路径</param>
 /// <returns>返回节点的值</returns>
 public static string GetNodeValue(XPathDocument xPath, string selectNode)
 {
     try
     {
         XPathNavigator xNav         = xPath.CreateNavigator();
         XPathNavigator xnSelectNode = xNav.SelectSingleNode(selectNode);
         return(xnSelectNode.InnerXml);
     }
     catch
     {
         return("");
     }
 }
コード例 #14
0
 /// <summary>
 /// 读取数据
 /// </summary>
 /// <param name="path">创建只读的Xml类</param>
 /// <param name="node">节点</param>
 /// <param name="attribute">属性名,非空时返回该属性值,否则返回串联值</param>
 /// <returns>string</returns>
 public static string GetNodeValue(XPathDocument xPath, string selectNode, string attribute)
 {
     try
     {
         XPathNavigator xNav         = xPath.CreateNavigator();
         XPathNavigator xnSelectNode = xNav.SelectSingleNode(selectNode);
         return(attribute == null ? xnSelectNode.InnerXml : xnSelectNode.GetAttribute(attribute, ""));
     }
     catch
     {
         return("");
     }
 }
コード例 #15
0
ファイル: AspxPageMenu.cs プロジェクト: akrisiun/git-dot-aspx
        public override void RenderHtml(TextWriter writer, XPathDocument xmlDoc)
        {
            if (isDebug > 0)
            {
                writer.WriteLine("[PageMenu=" + this.PrmAdd ?? "" + "]");
            }
            if (this.PrmAdd != null && PrmAdd.Contains("link="))
            {
                link = PrmAdd.Substring(5);
            }

            base.RenderHtml(writer, xmlDoc);
        }
コード例 #16
0
ファイル: Template.cs プロジェクト: Amitkapadi/WISP
 public static bool LoadTemplate(string template)
 {
     try
     {
         XPathDocument docNav = XMLHelper.LoadDocument(template, true);
         return(LoadTemplate(docNav));
     }
     catch (Exception e)
     {
         return(false);
     }
     return(false);
 }
コード例 #17
0
            public void SerializeOneStringArray()
            {
                var request = new XmlRpcRestRequest("some.method", true);
                var data    = new[]
                {
                    "one",
                    "two",
                    "three"
                };

                request.AddXmlRpcBody("", data);


                var requestBody = request.RequestBody();

                Assert.That(
                    requestBody,
                    Is.Not.Null,
                    "The request body parameter could not be found");

                if (requestBody == null)
                {
                    return;
                }
                ValidateXml(requestBody);

                using (var sr = new StringReader(requestBody)) {
                    var doc = new XPathDocument(sr);
                    var nav = doc.CreateNavigator();

                    Assert.That(
                        nav.Select("//methodCall/params/param").Count,
                        Is.EqualTo(2),
                        "There should be 2 parameters");

                    Assert.That(
                        nav.Select("//methodCall/params/param/value/string").Count,
                        Is.EqualTo(1),
                        "There should be 1 string parameter");

                    Assert.That(
                        nav.Select("//methodCall/params/param/value/array").Count,
                        Is.EqualTo(1),
                        "There should be 1 array parameter");

                    Assert.That(
                        nav.Select("//methodCall/params/param/value/array/data/value/string").Count,
                        Is.EqualTo(3),
                        "The array should have 3 (string) elements");
                }
            }
コード例 #18
0
        /* goodB2G() - use badsource and goodsink */
        private void GoodB2G(HttpRequest req, HttpResponse resp)
        {
            string data;

            while (true)
            {
                data = ""; /* initialize data in case id is not in query string */
                /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */
                {
                    if (req.QueryString["id"] != null)
                    {
                        data = req.QueryString["id"];
                    }
                }
                break;
            }
            while (true)
            {
                string xmlFile = null;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    /* running on Windows */
                    xmlFile = "..\\..\\CWE643_Xpath_Injection__Helper.xml";
                }
                else
                {
                    /* running on non-Windows */
                    xmlFile = "../../CWE643_Xpath_Injection__Helper.xml";
                }
                if (data != null)
                {
                    /* assume username||password as source */
                    string[] tokens = data.Split("||".ToCharArray());
                    if (tokens.Length < 2)
                    {
                        return;
                    }
                    /* FIX: validate input using StringEscapeUtils */
                    string username = System.Security.SecurityElement.Escape(tokens[0]);
                    string password = System.Security.SecurityElement.Escape(tokens[1]);
                    /* build xpath */
                    XPathDocument  inputXml = new XPathDocument(xmlFile);
                    XPathNavigator xPath    = inputXml.CreateNavigator();
                    string         query    = "//users/user[name/text()='" + username +
                                              "' and pass/text()='" + password + "']" +
                                              "/secret/text()";
                    string secret = (string)xPath.Evaluate(query);
                }
                break;
            }
        }
コード例 #19
0
ファイル: VehicleTab.cs プロジェクト: tools81/PnPVisualator
        private void gbxItem_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
            {
                string lvName = e.Data.GetData(DataFormats.Text).ToString();
                int    i      = gbxItem.Controls.Count;
                foreach (Control lvControl in gbxItem.Controls)
                {
                    if (lvControl is Label)
                    {
                        if (lvControl.Text == "...")
                        {
                            lvControl.Text = lvName;
                            break;
                        }
                    }
                }

                XPathDocument  lvItemXml = new XPathDocument(Properties.Settings.Default.DataLocation + "Lists/Item.xml");
                XPathNavigator nav       = lvItemXml.CreateNavigator();

                string lvType = nav.SelectSingleNode("Items/Item[@Name='" + lvName + "']/@Type").Value;

                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(Properties.Settings.Default.DataLocation + "Characters/" + Player.ShortName + ".xml");

                XmlNode xNode = xDoc.SelectSingleNode("Character/Equipment/" + lvType + "s/" + lvType + "[@Name='" + lvName + "']");
                xNode.ParentNode.RemoveChild(xNode);

                XmlElement   xElement = xDoc.CreateElement("Item");
                XmlAttribute xType    = xDoc.CreateAttribute("Type");
                xType.Value = lvType;
                xElement.Attributes.Append(xType);
                xElement.InnerText = lvName;

                XmlNode xEquipNode = xDoc.SelectSingleNode("Character/Vehicles/Vehicle[@Name='" + lblActiveVehicle.Text + "']/Cargo");
                xEquipNode.InsertAfter(xElement, xEquipNode.LastChild);

                FileStream lvFS = new FileStream(Properties.Settings.Default.DataLocation + "Characters/" + Player.ShortName + ".xml", FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
                xDoc.Save(lvFS);
                lvFS.Close();

                ClearCargoList();
                GetCargo();

                Character_Init cInit = new Character_Init(Player.ShortName);

                Trade lvTrade = new Trade();
                frmVisualator.setPanelToTrade(lvTrade);
            }
        }
コード例 #20
0
        public static Object3d GetByNumber(int stepId, int nb)
        {
            /* On déclare et on crée une instance des variables nécéssaires pour la recherche */
            Object3d obj = new Object3d();

            try
            {
                string rslt = Helper.service.LoadFile("etape.xml").ToString();

                StreamWriter sw = new StreamWriter(System.Windows.Forms.Application.StartupPath + "\\temp.xml");
                sw.Write(rslt);
                sw.Close();


                //XPathDocument XPathDocu = new XPathDocument((Stream)Helper.service.LoadFile("Experts.xml"));
                XPathDocument     XPathDocu = new XPathDocument(System.Windows.Forms.Application.StartupPath + "\\temp.xml");
                XPathNavigator    Navigator;
                XPathNodeIterator Nodes;
                /* On crée un navigateur */
                Navigator = XPathDocu.CreateNavigator();
                /* On crée ici l'expression XPath de recherche d'obj à  partir du login */
                string ExpXPath = "//objet[@nb='" + nb + "']";
                ExpXPath = "//etape[@id='" + stepId + "']//objet[@nb='" + nb + "']";
                /* On lance la recherche */
                Nodes = Navigator.Select(Navigator.Compile(ExpXPath));
                /* On vérifie si la recherche a été fructueuse */
                //System.Windows.Forms.MessageBox.Show("Nodes.Count: " + Nodes.Count, "XMLObject3d.GetByNumber");
                if (Nodes.Count != 0)
                {
                    Nodes.MoveNext(); // NOTE: Necéssaire pour se placer sur le noeud recherché
                    /* Encodage des données dans la classe Object3d */
                    //System.Windows.Forms.MessageBox.Show("Current: "+Nodes.Current.Name,"XMLObject3d.GetByNumber");
                    //System.Windows.Forms.MessageBox.Show("Current.id: " + Nodes.Current.GetAttribute("id", ""), "XMLObject3d.GetByNumber");
                    obj = GetById(Convert.ToInt32(Nodes.Current.GetAttribute("id", "")));
                    obj.setPath();
                    obj.setNb(nb);
                }
                /* Si aucun obj n'a été trouvé */
                else
                {
                    obj = null;
                }
            }
            catch (System.IO.FileNotFoundException x) { }
            catch (Exception x)
            {
                System.Windows.Forms.MessageBox.Show(x.ToString());
            }
            /* Renvoi de toutes les données dans une instance de la classe "Client" */
            return(obj);
        }
コード例 #21
0
        private async void applyTransformations(XPathDocument myXPathDoc)
        {
            XslCompiledTransform myXslTrans = new XslCompiledTransform();

            myXslTrans.Load("..\\..\\XPathGenerator.xslt");

            //Stream stream = new MemoryStream();
            //XmlWriter writer = XmlWriter.Create(stream);
            //stream.Position = 0;

            XmlTextWriter myWriter = new XmlTextWriter("result.html", null);
            XmlDocument   doc      = new XmlDocument();

            doc.LoadXml(this.XmlText);
            XmlReader xmlReadB = new XmlTextReader(new StringReader(doc.DocumentElement.OuterXml));

            myXslTrans.Transform(xmlReadB, null, myWriter);
            myWriter.Close();

            string filename = @"result.html";

            char[]        result;
            StringBuilder builder = new StringBuilder("Sample XPaths: \n");

            using (StreamReader reader = File.OpenText(filename))
            {
                result = new char[reader.BaseStream.Length];
                await reader.ReadAsync(result, 0, (int)reader.BaseStream.Length);
            }
            List <string> XpathList = new List <string>();
            StringBuilder line      = new StringBuilder();

            foreach (char c in result)
            {
                builder.Append(c);
                line.Append(c);
                if (c == '\n')
                {
                    XpathList.Add(line.ToString());
                    line.Clear();
                }
            }

            listBox1.DataSource = XpathList;

            generateNodeElementsList();

            //XPathExamples.ResetText();
            //XPathExamples.AppendText(builder.ToString());
            Console.WriteLine(builder.ToString());
        }
コード例 #22
0
        private XPathDocument GetDocument(string file)
        {
            string path = Path.Combine(_directory, file);

            if (File.Exists(path))
            {
                XPathDocument document = new XPathDocument(path);
                return(document);
            }
            else
            {
                return(null);
            }
        }
コード例 #23
0
ファイル: SignatureInfo.cs プロジェクト: zzy092/npoi
        /**
         * add the xml signature to the document
         *
         * @throws XMLSignatureException
         * @throws MarshalException
         */
        public void ConfirmSignature()
        {
            XPathDocument document = DocumentHelper.CreateDocument();

            // operate
            //DigestInfo digestInfo = preSign(document, null);

            // Setup: key material, signature value
            //byte[] signatureValue = signDigest(digestInfo.digestValue);

            // operate: postSign
            //postSign(document, signatureValue);
            throw new NotImplementedException();
        }
コード例 #24
0
ファイル: Storage.cs プロジェクト: sgtnasty/battle
        public static List <SpeciesDefinition> LoadSpecies(string xmlfile)
        {
            List <SpeciesDefinition> species = new List <SpeciesDefinition>();
            XPathDocument            doc     = new XPathDocument(xmlfile);
            XPathNavigator           nav     = doc.CreateNavigator();

            foreach (XPathNavigator n in nav.Select("/battle/speciess/species"))
            {
                string            name  = n.GetAttribute("name", "");
                string            descr = n.GetAttribute("description", "");
                SpeciesDefinition d     = new SpeciesDefinition();
                d.Name        = name;
                d.Description = descr;

                /*
                 * foreach (XPathNavigator n1 in n.Select("origin"))
                 * {
                 *      string oriname = n.GetAttribute("name", "");
                 *
                 *      //d.AddOrigin(n.GetAttribute("name",""));
                 * }
                 */
                foreach (XPathNavigator n2 in n.Select("provides"))
                {
                    d.Provide(n2.GetAttribute("value", ""));
                }
                foreach (XPathNavigator n3 in n.Select("requires"))
                {
                    d.Require(n3.GetAttribute("value", ""));
                }
                foreach (XPathNavigator n4 in n.Select("modifier"))
                {
                    string             modname     = n4.GetAttribute("name", "");
                    string             description = n4.GetAttribute("description", "");
                    string             val         = n4.GetAttribute("value", "");
                    string             target      = n4.GetAttribute("target", "");
                    string             type        = n4.GetAttribute("type", "");
                    ModifierDefinition mod         = new ModifierDefinition();
                    mod.Name        = modname;
                    mod.Description = description;
                    mod.ModValue    = double.Parse(val);
                    mod.EntityType  = BattleEntity.ParseEntity(type);
                    mod.TargetName  = target;
                    d.AddModifier(mod);
                }
                species.Add(d);
            }

            return(species);
        }
コード例 #25
0
        private static ByteProcessor ProcessXpath(params string[] expressions)
        {
            var strexpr = string.Join(" | ", expressions);
            var expr    = XPathExpression.Compile(strexpr);

            return(delegate(FileEntry fe, PackageFileEntry pfe, byte[] data)
            {
                var datastring = System.Text.Encoding.UTF8.GetString(data);
                using var tidiedstring = new StringReader(XmlTidier.TidyString(datastring));
                var xd = new XPathDocument(tidiedstring);
                var nodes = xd.CreateNavigator().Select(expr);
                return nodes.Cast <XPathNavigator>().Select(i => i.Value);
            });
        }
コード例 #26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlCommentDocumentationProvider" /> class.
        /// </summary>
        /// <param name="documentPaths">The document paths.</param>
        public XmlCommentDocumentationProvider(IEnumerable <string> documentPaths)
        {
            this.documentNavigators = new List <XPathNavigator>();

            foreach (var documentPath in documentPaths)
            {
                var path = HttpContext.Current.Server.MapPath(documentPath);

                // Load documentation xml
                var xpath = new XPathDocument(path);

                this.documentNavigators.Add(xpath.CreateNavigator());
            }
        }
コード例 #27
0
        private IEnumerable <YahooAddress> ProcessWebResponse(WebResponse response)
        {
            XPathDocument  xmlDoc = LoadXmlResponse(response);
            XPathNavigator nav    = xmlDoc.CreateNavigator();

            YahooError error = EvaluateError(Convert.ToInt32(nav.Evaluate("number(/ResultSet/Error)")));

            if (error != YahooError.NoError)
            {
                throw new YahooGeocodingException(error);
            }

            return(ParseAddresses(nav.Select("/ResultSet/Result")).ToArray());
        }
コード例 #28
0
ファイル: test.cs プロジェクト: mono/gert
	static void Test2 ()
	{
		XmlSchemaSet schemaSet = new XmlSchemaSet ();
		schemaSet.Add (null, "test.xsd");

		XmlReaderSettings settings = new XmlReaderSettings ();
		settings.ValidationType = ValidationType.Schema;
		settings.CloseInput = true;
		settings.Schemas.Add (schemaSet);

		XmlReader r = XmlReader.Create ("test.xml", settings);
		XPathDocument d = new XPathDocument (r);
		d.CreateNavigator ();
	}
        /// <summary>
        /// Initializes the syndication extension using the supplied <see cref="XmlReader"/>.
        /// </summary>
        /// <param name="reader">The <b>XmlReader</b> used to load this <see cref="WellFormedWebCommentsSyndicationExtension"/>.</param>
        /// <returns><b>true</b> if the <see cref="WellFormedWebCommentsSyndicationExtension"/> was able to be initialized using the supplied <paramref name="reader"/>; otherwise <b>false</b>.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="reader"/> is a null reference (Nothing in Visual Basic).</exception>
        public override bool Load(XmlReader reader)
        {
            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(reader, "reader");

            //------------------------------------------------------------
            //	Create navigator against reader and pass to load method
            //------------------------------------------------------------
            XPathDocument document = new XPathDocument(reader);

            return(this.Load(document.CreateNavigator()));
        }
コード例 #30
0
 public void IncludeXmlComments(string filePath)
 {
     if (File.Exists(filePath))
     {
         try
         {
             var xPath = new XPathDocument(filePath);
             _xmlDocFactories.Add(() => xPath);
         }
         catch {}
     }
     else
         throw new FileNotFoundException("XML Comment file not found!");
 }
コード例 #31
0
        protected override void Load(string _strXslFile, string _strXmlFile)
        {
#pragma warning disable 0618
            XmlValidatingReader xrData = new XmlValidatingReader(new XmlTextReader(Path.Combine(_strPath, _strXmlFile)));
#pragma warning restore 0618
            _xd = new XPathDocument(xrData, XmlSpace.Preserve);
            xrData.Dispose();

#pragma warning disable 0618
            XmlValidatingReader xrTemp = new XmlValidatingReader(new XmlTextReader(Path.Combine(_strPath, _strXslFile)));
            xrTemp.ValidationType = ValidationType.None;
            xrTemp.EntityHandling = EntityHandling.ExpandEntities;
            xsltSameInstance.Load(xrTemp);
        }
コード例 #32
0
        public void SimpleReading()
        {
            XPathDocument doc = new XPathDocument(new StringReader(
                                                      "<customer id='1' pp:id='aba' xmlns='urn-kzu' xmlns:pp='urn-pepenamespace'><order id='1'>Chocolates</order></customer>"));
            XPathNavigator nav = doc.CreateNavigator();

            XmlReader reader = new XPathNavigatorReader(nav);

            reader.Read();
            Assert.AreEqual("customer", reader.LocalName);
            Assert.AreEqual("urn-kzu", reader.NamespaceURI);
            Assert.AreEqual(4, reader.AttributeCount);
            // @id
            reader.MoveToFirstAttribute();
            Assert.AreEqual("id", reader.LocalName);
            // @pp:id
            reader.MoveToNextAttribute();
            Assert.AreEqual("id", reader.LocalName);
            Assert.AreEqual("urn-pepenamespace", reader.NamespaceURI);
            // xmlns="urn-kzu" and xmlns:pp="urn-pepenamespace". Order is not guaranteed.
            reader.MoveToNextAttribute();
            Assert.AreEqual(XmlNamespaces.XmlNs, reader.NamespaceURI);
            reader.MoveToNextAttribute();
            Assert.AreEqual(XmlNamespaces.XmlNs, reader.NamespaceURI);

            reader.Read();
            Assert.AreEqual("order", reader.LocalName);
            Assert.AreEqual("urn-kzu", reader.NamespaceURI);
            Assert.AreEqual(1, reader.AttributeCount);
            reader.MoveToFirstAttribute();
            Assert.AreEqual("id", reader.LocalName);
            Assert.IsTrue(reader.ReadAttributeValue());
            Assert.AreEqual("1", reader.Value);
            Assert.IsFalse(reader.MoveToNextAttribute());

            reader.Read();
            Assert.AreEqual(XmlNodeType.Text, reader.NodeType);
            Assert.AreEqual("Chocolates", reader.Value);

            reader.Read();
            Assert.AreEqual("order", reader.LocalName);
            Assert.AreEqual(XmlNodeType.EndElement, reader.NodeType);

            reader.Read();
            Assert.AreEqual("customer", reader.LocalName);
            Assert.AreEqual(XmlNodeType.EndElement, reader.NodeType);

            reader.Read();
            Assert.AreEqual(ReadState.EndOfFile, reader.ReadState);
        }
コード例 #33
0
        public static XPathDocument GetNavigableDocument(Stream stream)
        {
            if (stream == null)
            {
                return(null);
            }
            if (stream.Position != 0)
            {
                stream.Position = 0;
            }
            XPathDocument d = new XPathDocument(stream);

            return(d);
        }
コード例 #34
0
        private void ReadXML()
        {
            string assemblyFile = (new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;
            var    doc          = new XPathDocument(AppDomain.CurrentDomain.BaseDirectory + "\\Connection.xml");
            var    navigator    = doc.CreateNavigator();

            DataSource         = navigator.SelectSingleNode("//appsettings/ServerName").ToString();
            ServerPort         = navigator.SelectSingleNode("//appsettings/ServerPort").ToString();
            UserID             = navigator.SelectSingleNode("//appsettings/UserName").ToString();
            Password           = navigator.SelectSingleNode("//appsettings/Password").ToString();
            InitialCatalog     = navigator.SelectSingleNode("//appsettings/Database").ToString();
            IntegratedSecurity = navigator.SelectSingleNode("//appsettings/IntegratedSecurity").ToString();
            //  TrustedConnection = navigator.SelectSingleNode("//appsettings/TrustedConnection").ToString();
        }
コード例 #35
0
        public void Load()
        {
            if (!Exists())
            {
                return;
            }

            using (MemoryStream stream = new MemoryStream(_fileSystem.ReadAllBytes(_filename)))
            {
                _document  = new XPathDocument(stream);
                _navigator = _document.CreateNavigator();
            }
            _isLoaded = true;
        }
        /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
        private void GoodB2G2()
        {
            string data;

            if (5 == 5)
            {
                /* get environment variable ADD */
                /* POTENTIAL FLAW: Read data from an environment variable */
                data = Environment.GetEnvironmentVariable("ADD");
            }
            else
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure data is inititialized before the Sink to avoid compiler errors */
                data = null;
            }
            if (5 == 5)
            {
                string xmlFile = null;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    /* running on Windows */
                    xmlFile = "..\\..\\CWE643_Xpath_Injection__Helper.xml";
                }
                else
                {
                    /* running on non-Windows */
                    xmlFile = "../../CWE643_Xpath_Injection__Helper.xml";
                }
                if (data != null)
                {
                    /* assume username||password as source */
                    string[] tokens = data.Split("||".ToCharArray());
                    if (tokens.Length < 2)
                    {
                        return;
                    }
                    /* FIX: validate input using StringEscapeUtils */
                    string username = System.Security.SecurityElement.Escape(tokens[0]);
                    string password = System.Security.SecurityElement.Escape(tokens[1]);
                    /* build xpath */
                    XPathDocument  inputXml = new XPathDocument(xmlFile);
                    XPathNavigator xPath    = inputXml.CreateNavigator();
                    string         query    = "//users/user[name/text()='" + username +
                                              "' and pass/text()='" + password + "']" +
                                              "/secret/text()";
                    string secret = (string)xPath.Evaluate(query);
                }
            }
        }
コード例 #37
0
        public void ParseXml(string serviceParametersXml)
        {
            this.Clear();

            if (string.IsNullOrEmpty(serviceParametersXml))
            {
                return;
            }

            StringReader xPathTextReader = null;

            try
            {
                xPathTextReader = new StringReader(serviceParametersXml);
                XPathDocument xPathDoc = new XPathDocument(xPathTextReader);

                XPathNavigator    xPathNavigator = xPathDoc.CreateNavigator();
                XPathNodeIterator xPathIter      =
                    xPathNavigator.Select("/ServiceParameters/Item");

                while (xPathIter.MoveNext())
                {
                    string key =
                        xPathIter.Current?.GetAttribute("key", xPathIter.Current.NamespaceURI);
                    if (string.IsNullOrEmpty(key))
                    {
                        continue;
                    }

                    string value = xPathIter.Current?.Value;

                    if (string.CompareOrdinal(key, "PublicKey") == 0)
                    {
                        this.PublicKey = value;

                        continue;
                    }

                    base[key] = value;
                }
            }
            catch (Exception)
            {
                // Just Handle Exceptions
            }
            finally
            {
                xPathTextReader?.Close();
            }
        }
コード例 #38
0
        public void Load(string _strXslFile, string _strXmlFile)
        {
            _xrData = XmlReader.Create(_strPath + _strXmlFile);
            _xd     = new XPathDocument(_xrData, XmlSpace.Preserve);
            _xrData.Dispose();

            XmlReaderSettings xrs = new XmlReaderSettings();

#pragma warning disable 0618
            xrs.ProhibitDtd = false;
#pragma warning restore 0618
            XmlReader xrTemp = XmlReader.Create(_strPath + _strXslFile, xrs);
            xsltSameInstance.Load(xrTemp);
        }
コード例 #39
0
ファイル: User.cs プロジェクト: cupid0426/MyProject
        public void CreatePersonalInfo(string xml)
        {
            TextReader        reader = new StringReader(xml);
            XPathDocument     doc    = new XPathDocument(reader);
            XPathNavigator    nav    = ((IXPathNavigable)doc).CreateNavigator();
            XPathNodeIterator iter   = nav.Select("/results/user-info/personal");

            iter.MoveNext();
            this.nickname = iter.Current.GetAttribute("nickname", string.Empty);
            this.impresa  = iter.Current.GetAttribute("impresa", string.Empty);
            this.name     = iter.Current.GetAttribute("name", string.Empty);
            this.mobileNo = long.Parse(iter.Current.GetAttribute("mobile-no", string.Empty));
            this.gender   = int.Parse(iter.Current.GetAttribute("gender", string.Empty));
        }
コード例 #40
0
ファイル: main.cs プロジェクト: jonnenauha/code
    public XRDParser(Stream xrd)
    {
        doc_ = new XPathDocument (xrd);
        result_ = new XRDDocument ();
        cursor_ = doc_.CreateNavigator();

        expires_exp_ = cursor_.Compile ("/XRD/Expires");
        subject_exp_ = cursor_.Compile ("/XRD/Subject");
        aliases_exp_ = cursor_.Compile ("/XRD/Alias");
        types_exp_ = cursor_.Compile ("/XRD/Type");

        link_rel_exp_ = cursor_.Compile ("/XRD/Link/Rel");
        link_uri_exp_ = cursor_.Compile ("/XRD/Link/URI");
        link_mediatype_exp_ = cursor_.Compile ("/XRD/Link/MediaType");
    }
コード例 #41
0
ファイル: Program.cs プロジェクト: xs2ranjeet/13ns9-1spr
 static void Main ()
 {
     XPathDocument doc = new XPathDocument("..//..//..//..//Cars.xml");
     XPathNavigator nav = doc.CreateNavigator();
     XPathNodeIterator iterator = nav.Select("/Cars/Car");
     while (iterator.MoveNext())
     {
         XPathNodeIterator it = iterator.Current.Select("Manufactured");
         it.MoveNext();
         string manufactured = it.Current.Value;
         it = iterator.Current.Select("Model");
         it.MoveNext();
         string model = it.Current.Value;
         Console.WriteLine("{0} {1}", manufactured, model);
     }
 }
コード例 #42
0
ファイル: test.cs プロジェクト: mono/gert
	static void Test1 ()
	{
		string xml = "<root><child1><nest1><nest2>hello!</nest2></nest1></child1><child2/><child3/></root>";
		XmlReader r = new XmlTextReader (new StringReader (xml));

		while (r.Read ()) {
			if (r.Name == "child1")
				break;
		}

		XPathDocument d = new XPathDocument (r);
		XPathNavigator n = d.CreateNavigator ();
		string expected = string.Format ("<child1>{0}  <nest1>{0}    <nest2>hello!</nest2>{0}  </nest1>{0}</child1>{0}<child2 />{0}<child3 />",
			Environment.NewLine);

		Assert.AreEqual (expected, n.OuterXml, "#1");
	}
コード例 #43
0
    public static void Transform(string sXmlPath, string sXslPath)
    {
        try {
        XPathDocument myXPathDoc = new XPathDocument(sXmlPath);
        XslCompiledTransform myXslTrans = new XslCompiledTransform();
        myXslTrans.Load(sXslPath);
        XsltArgumentList xslArgs = new XsltArgumentList();
        Utils classPtr = new Utils();
        xslArgs.AddExtensionObject("urn:util", classPtr);
        XmlTextWriter myWriter = new XmlTextWriter("result.xml", null);
        myXslTrans.Transform(myXPathDoc, xslArgs, myWriter);
        myWriter.Close();
        } catch (Exception e) {

        Console.WriteLine("Exception: {0}", e.ToString());
        }
    }
コード例 #44
0
    public static void Main (string [] args)
    {
        var queries = new [] {
            "/Addin/@name",
            "/Addin/@description",
            "/Addin/@category"
        };

        Console.WriteLine (@"// Generated - Do Not Edit!

internal static class AddinXmlStringCatalog
{
    private static void Strings ()
    {");

        var paths = new List<string> (args);
        paths.Sort ();

        var blacklist = new string [] { "GStreamer", "Gnome", "Osx", "Unix", "MeeGo", "Gio", "NowPlaying",
            "Hal", "src/Core", "Banshee.Dap/", "RemoteAudio", "Sample", "SqlDebugConsole", "Template", "Windows" };

        foreach (var path in paths) {
            if (blacklist.Any (path.Contains))
                continue;

            Console.WriteLine ("        // {0}", path);
            var xpath = new XPathDocument (path);
            var nav = xpath.CreateNavigator ();
            foreach (var query in queries) {
                var iter = nav.Select (query);
                while (iter.MoveNext ()) {
                    var value = iter.Current.Value.Trim ();
                    if (String.IsNullOrEmpty (value) ||
                        value[0] == '@' ||
                        (iter.Current.Name == "category" && value.StartsWith ("required:"))) {
                        continue;
                    }
                    Console.WriteLine (@"        Catalog.GetString (@""{0}"");",
                        value.Replace (@"""", @""""""));
                }
            }
            Console.WriteLine ();
        }

        Console.WriteLine ("    }\n}");
    }
コード例 #45
0
  } //Main()

  /// <summary>
  /// Demonstrates the XslTransform class using two different overloads.
  /// One returns an XmlReader containing the transform.
  /// The other stores the transform in an XmlTextWriter.
  /// </summary>
  /// <param name="document"></param>
  /// <param name="stylesheet"></param>
  public static void ReadTransformWrite(string document, string stylesheet)
  {
    StreamReader stream = null;

    try
    {
      string outputFile = Path.GetFileNameWithoutExtension(document) + "_transform.xml";
      // XPathDocument stores the target XML in an efficient way for transformation.
      XPathDocument myXPathDocument = new XPathDocument(document);
      XslTransform myXslTransform = new XslTransform();
      myXslTransform.Load(stylesheet);

      // Get back the transform results in an XMLReader and output them to the console.
      XmlReader reader = myXslTransform.Transform(myXPathDocument, null);

      Console.WriteLine("Input XML file: {0} \nXSL stylesheet: {1}" + nl, document, stylesheet);
      Console.WriteLine(nl + "Layout of transformed XML content from XML reader:" + nl);
      OutputXml(reader);

      // Create an output file to hold the tranform.
      // Using an intermediate XmlTextWriter instead of the overload of the Transform method
      // that writes directly to a file allows more control of the formatting.
      XmlTextWriter writer = new XmlTextWriter(outputFile, null);
      writer.Formatting = Formatting.Indented;
      writer.Indentation = 2;
      myXslTransform.Transform(myXPathDocument, null, writer);
      writer.Close();

      //Output the contents of the tranformed file to the console.
      Console.WriteLine(nl + "Transformed XML content from file:" + nl);
      stream = new StreamReader (outputFile);
      Console.Write(stream.ReadToEnd());
    } //try

    catch (Exception e)
    {
      Console.WriteLine ("Exception: {0}", e.ToString());
    } //catch

    finally
    {
      if (stream != null)
        stream.Close();
    } //finally
  } //ReadTransformWrite()
コード例 #46
0
ファイル: Program.cs プロジェクト: irinalesina/ITStepProjects
    static void Main()
    {
        XPathDocument doc = new XPathDocument(@"D:\irinalesina\C#\ClassWork\13_xPath\13_xPath\Cars.xml");
        XPathNavigator nav = doc.CreateNavigator();
        XPathNodeIterator iterator = nav.Select("//Car[Color/@metallic]");
        while (iterator.MoveNext())
        {
            XPathNodeIterator it = iterator.Current.Select("Manufactured");
            it.MoveNext();
            string manufactured = it.Current.Value;
            it = iterator.Current.Select("Model");
            it.MoveNext();
            string model = it.Current.Value;
            Console.WriteLine("{0} {1}", manufactured, model);
        }

        Console.ReadKey();
    }
コード例 #47
0
ファイル: Program.cs プロジェクト: sreeshprakash/Web_Services
 //This will transform xml document using xslt and produce result xml document
 //and display it
 public static void Main(string[] args)
 {
     try
     {
         XPathDocument myXPathDocument = new XPathDocument("C:/Users/user/Desktop/Assignment 4/schema.xml");
         XslTransform myXslTransform = new XslTransform();
         XmlTextWriter writer = new XmlTextWriter("C:/Users/user/Desktop/Assignment 4/output.html", null);
         myXslTransform.Load("http://www.public.asu.edu/~sprakas3/dsod/Hotels.xsl");
         myXslTransform.Transform(myXPathDocument, null, writer);
         writer.Close();
         StreamReader stream = new StreamReader("C:/Users/user/Desktop/Assignment 4/output.html");
         Console.Write("**This is result document**\n\n");
         Console.Write(stream.ReadToEnd());
     }
     catch (Exception e)
     {
     }
 }
コード例 #48
0
 public static void Main(string[] args)
 {
     try
     {
         String xmlDoc = "C:\\Path\\To\\Input.xml"
         String xslDoc = "C:\\Path\\To\\XSLT_Script.xsl"
         String newDoc = "C:\\Path\\To\\Output.xml"
         
         XPathDocument myXPathDocument = new XPathDocument(xmlDoc);
         XslTransform myXslTransform = new XslTransform();
                     
         myXslTransform.Load(xslDoc);
         myXslTransform.Transform(myXPathDocument, newDoc);
     }
     catch (Exception e)
     {
         Console.WriteLine ("Exception: {0}", e.ToString());
     }
 }
コード例 #49
0
ファイル: Program.cs プロジェクト: notox/Hello-World
    static void Main(string[] args)
    {
        XPathDocument document = new XPathDocument("contosoBooks.xml");
        XPathNavigator navigator = document.CreateNavigator();

        navigator.MoveToChild("bookstore", "http://www.contoso.com/books");
        navigator.MoveToChild("book", "http://www.contoso.com/books");

        // Select all the descendant nodes of the book node.
        XPathNodeIterator bookDescendants = navigator.SelectDescendants("", "http://www.contoso.com/books", false);

        // Display the LocalName of each descendant node.
        Console.WriteLine("Descendant nodes of the book node:");
        while (bookDescendants.MoveNext())
        {
            Console.WriteLine(bookDescendants.Current.Name);
        }

        // Select all the child nodes of the book node.
        XPathNodeIterator bookChildren = navigator.SelectChildren("", "http://www.contoso.com/books");

        // Display the LocalName of each child node.
        Console.WriteLine("\nChild nodes of the book node:");
        while (bookChildren.MoveNext())
        {
            Console.WriteLine(bookChildren.Current.Name);
        }

        // Select all the ancestor nodes of the title node.
        navigator.MoveToChild("title", "http://www.contoso.com/books");

        XPathNodeIterator bookAncestors = navigator.SelectAncestors("", "http://www.contoso.com/books", false);

        // Display the LocalName of each ancestor node.
        Console.WriteLine("\nAncestor nodes of the title node:");

        while (bookAncestors.MoveNext())
        {
            Console.WriteLine(bookAncestors.Current.Name);
        }
        Console.ReadKey();
    }
コード例 #50
0
    public static void Main (string [] args)
    {
        var queries = new [] {
            "/Addin/@name",
            "/Addin/@description",
            "/Addin/@category",
            "/Addin/Extension/Command/@_label",
            "/Addin/Extension/ExportMenuItem/@_label"
        };

        Console.WriteLine (@"// Generated - Do Not Edit!

internal static class AddinXmlStringCatalog
{
    private static void Strings ()
    {");

        var paths = new List<string> (args);
        paths.Sort ();

        foreach (var path in paths) {
            Console.WriteLine ("        // {0}", path);
            var xpath = new XPathDocument (path);
            var nav = xpath.CreateNavigator ();
            foreach (var query in queries) {
                var iter = nav.Select (query);
                while (iter.MoveNext ()) {
                    var value = iter.Current.Value.Trim ();
                    if (String.IsNullOrEmpty (value) ||
                        value[0] == '@' ||
                        (iter.Current.Name == "category" && value.StartsWith ("required:"))) {
                        continue;
                    }
                    Console.WriteLine (@"        Catalog.GetString (@""{0}"");",
                        value.Replace (@"""", @""""""));
                }
            }
            Console.WriteLine ();
        }

        Console.WriteLine ("    }\n}");
    }
コード例 #51
0
    public bool Parse(string data)
    {
        //TODO: add error handling
        XmlTextReader reader = new XmlTextReader(new StringReader(data));
        doc = new XPathDocument(reader);
        nsman = new XmlNamespaceManager(reader.NameTable);

        // Add all namespaces that are declared in the root element of the document to the
        // namespaces map, so that they can be used in xpath selectors.
        // Namespaces that are declared anywhere else in the document will not be usable (the
        // XML spec allow declaring them not on the root, but i don't think it's very common,
        // but i may be wrong).
        XPathNavigator nav = doc.CreateNavigator();
        nav.MoveToChild(XPathNodeType.Element);
        IDictionary<string, string> nsis = nav.GetNamespacesInScope(XmlNamespaceScope.Local);
        foreach (KeyValuePair<string, string> nsi in nsis) {
            string prefix = (nsi.Key == string.Empty) ? "global" : nsi.Key;
            nsman.AddNamespace(prefix, nsi.Value);
        }
        return true;
    }
コード例 #52
0
ファイル: Default.aspx.cs プロジェクト: kacecode/SchoolWork
    protected void Page_Load(object sender, EventArgs e)
    {
        //Load document
        string booksFile = Server.MapPath("books.xml");

        XPathDocument document = new XPathDocument(booksFile);
        XPathNavigator nav = document.CreateNavigator();

        //Add a namespace prefix that can be used in the XPath expression
        XmlNamespaceManager namespaceMgr = new XmlNamespaceManager(nav.NameTable);
        namespaceMgr.AddNamespace("b", "http://example.books.com");

        //All books whose price is not greater than 10.00
        foreach (XPathNavigator node in
            nav.Select("//b:book[not(b:price[. > 10.00])]/b:price",
            namespaceMgr))
        {
            Decimal price = (decimal)node.ValueAs(typeof(decimal));
            Response.Write(String.Format("Price is {0}<BR/>",
                price));
        }
    }
コード例 #53
0
	protected void downloadUpdates_Click(object sender, EventArgs e) {
		var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager);
		XPathDocument updates = new XPathDocument(TwitterConsumer.GetUpdates(twitter, this.AccessToken).CreateReader());
		XPathNavigator nav = updates.CreateNavigator();
		var parsedUpdates = from status in nav.Select("/statuses/status").OfType<XPathNavigator>()
							where !status.SelectSingleNode("user/protected").ValueAsBoolean
							select new {
								User = status.SelectSingleNode("user/name").InnerXml,
								Status = status.SelectSingleNode("text").InnerXml,
							};

		StringBuilder tableBuilder = new StringBuilder();
		tableBuilder.Append("<table><tr><td>Name</td><td>Update</td></tr>");

		foreach (var update in parsedUpdates) {
			tableBuilder.AppendFormat(
				"<tr><td>{0}</td><td>{1}</td></tr>",
				HttpUtility.HtmlEncode(update.User),
				HttpUtility.HtmlEncode(update.Status));
		}
		tableBuilder.Append("</table>");
		resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() });
	}
コード例 #54
0
ファイル: global.asax.cs プロジェクト: Bert6623/Gedcom.Net
	protected void Application_Start(object sender, EventArgs e)
	{
		if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["gedcomDirectory"]))
		{
			Application["GedcomDirectory"] = ConfigurationManager.AppSettings["gedcomDirectory"].Trim();		
		}
		else
		{
			throw new Exception("gedcomDirectory required in site.config");	
		}
		
		if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["gedcomFile"]))
		{
			Application["GedcomFile"] = ConfigurationManager.AppSettings["gedcomFile"].Trim();		
		}
		else
		{
			throw new Exception("gedcomFile required in site.config");	
		}
		
		if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["xslDirectory"]))
		{
			Application["XSLDirectory"] = ConfigurationManager.AppSettings["xslDirectory"].Trim();		
		}
		else
		{
			throw new Exception("xslDirectory required in site.config");	
		}
		
		string xmlFile = Path.Combine((string)Application["GedcomDirectory"], (string)Application["GedcomFile"]);
		
		XPathDocument doc = new XPathDocument(xmlFile);
			
		
		Application["XMLDoc"] = doc;
	}
コード例 #55
0
ファイル: OrderPage.aspx.cs プロジェクト: TCarmack/Brentwood
    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        int jobID = -1;
        JobInfo info = new JobInfo();
        Control currentControl = null;
        int jobTypeID = int.Parse(Session["JobTypeID"].ToString());
        string specialInstructions = "";
        int quantity = -1;
        string deliveryOrPickup = "";
        Guid customerID = Guid.Empty;
        DateTime promiseDate = DateTime.Today.AddYears(-400);
        List<string> jobAssets = new List<string>();
        List<JobInfo> jobInfo = new List<JobInfo>();
        bool getFiles = false;

        string filename = Server.MapPath("../../Admin/Settings.xml");
        XPathDocument document = new XPathDocument(filename);
        XPathNavigator navigator = document.CreateNavigator();
        XPathExpression expression = navigator.Compile("/appSettings/initialJobStatus");
        XPathNodeIterator iterator = navigator.Select(expression);
        iterator.MoveNext();
        XPathNavigator nav2 = iterator.Current.Clone();
        int jobStatus = Brentwood.GetJobStatusByName("Pending Approval").JobStatusID;

        try
        {
            customerID = (Brentwood.LookupCustomerByUsername(User.Identity.Name)).UserId;
            promiseDate = Utils.GetPromiseDate(jobTypeID);
        }
        catch (Exception ex)
        {
            FormMessage.Text = ex.Message;
            FormMessage.ForeColor = Color.Red;
        }

        foreach (HtmlTableRow row in ((HtmlTable)Session["CurrentForm"]).Rows)
        {
            info = new JobInfo();
            info.NameKey = (row.Cells[0].Controls[0] as Label).Text;
            currentControl = FormPanel.FindControl(row.Cells[1].Controls[0].ID);

            if (currentControl.ID == "500TextBoxQuantityTextbox")
            {
                if ((currentControl as TextBox).Text != "")
                {
                    quantity = int.Parse((currentControl as TextBox).Text.Trim());
                }
            }
            else if (currentControl.ID == "501TextBoxSpecialInstructionsTextbox")
            {
                specialInstructions = (currentControl as TextBox).Text.Trim();
            }
            else if (currentControl.ID == "502CheckBoxDeliveryCheckbox")
            {
                if ((currentControl as CheckBox).Checked)
                {
                    deliveryOrPickup = "D";
                }
                else
                {
                    deliveryOrPickup = "P";
                }
            }
            else
            {
                if (row.Cells[1].Controls[0] is TextBox)
                {
                    info.DataValue = ((TextBox)currentControl).Text.Trim();
                    jobInfo.Add(info);
                }
                else if (row.Cells[1].Controls[0] is CheckBox)
                {
                    if (((CheckBox)currentControl).Checked)
                    {
                        info.DataValue = "true";
                        jobInfo.Add(info);
                    }
                    else
                    {
                        info.DataValue = "false";
                        jobInfo.Add(info);
                    }
                }
                else if (row.Cells[1].Controls[0] is Controls_MultiFileUpload)
                {
                    getFiles = true;
                }
                else
                {
                    FormMessage.Text = "Control type invalid.";
                    FormMessage.ForeColor = Color.Red;
                }
            }
        }

        try
        {
            jobID = Brentwood.AddJob(jobTypeID, specialInstructions, quantity, deliveryOrPickup, customerID, promiseDate);
            Brentwood.InitializeJobJobStatus(jobID, (Brentwood.LookupCustomerByUsername(User.Identity.Name.ToString())).UserId);
            Brentwood.AddInfoToJob(jobInfo, jobID);

            if (getFiles)
            {
                string physicalPath = "";
                string virtualPath = "";

                // Get the HttpFileCollection
                HttpFileCollection hfc = Request.Files;
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.ContentLength > 0)
                    {
                        physicalPath = WebUtils.GetFolderPath(User.Identity.Name, jobID, Server) + "\\" + System.IO.Path.GetFileName(hpf.FileName);
                        virtualPath = WebUtils.ResolveVirtualPath(physicalPath);

                        hpf.SaveAs(Server.MapPath(virtualPath));
                        jobAssets.Add(physicalPath);
                    }
                }
            }

            Brentwood.AddAssetsToJob(jobAssets, jobID);

            FormMessage.Text = "Job successfully submitted!";
            FormMessage.ForeColor = Color.Green;

            Context.Items.Add("JobID", jobID);
            Server.Transfer("OrderCompletePage.aspx");
        }
        catch (Exception ex)
        {
            FormMessage.Text = ex.Message;
            FormMessage.ForeColor = Color.Red;
        }
        //End of SubmitButton_Click method
    }
コード例 #56
0
 private string GetFromXPath(string XML, string XPath)
 {
     if (XML.Trim() == "")
     {
         return "";
     }
     string str = "";
     try
     {
         XPathDocument document = new XPathDocument(new StringReader(XML));
         XPathNodeIterator iterator = document.CreateNavigator().Select(XPath);
         while (iterator.MoveNext())
         {
             str = str + iterator.Current.Value;
         }
     }
     catch
     {
         return "";
     }
     return str;
 }
コード例 #57
0
ファイル: AssemblyItem.cs プロジェクト: rubenv/bockbuild
    private static string FindNativeLibraryForDllMap(string asmConfig, string pinvokeModule)
    {
        var navigator = new XPathDocument (asmConfig).CreateNavigator ();
        var expression = navigator.Compile ("/configuration/dllmap");
        var iter = navigator.Select (expression);

        while (iter.MoveNext ()) {
            if (iter.Current.GetAttribute ("dll", navigator.NamespaceURI) != pinvokeModule) {
                continue;
            }

            // FIXME: make this configurable on the confinement
            var os = iter.Current.GetAttribute ("os", navigator.NamespaceURI);
            if (String.IsNullOrEmpty (os) || os == "osx" || os == "!windows") {
                return iter.Current.GetAttribute ("target", navigator.NamespaceURI);
            }
        }

        return pinvokeModule;
    }
コード例 #58
0
ファイル: Receive.aspx.cs プロジェクト: ichari/ichari
    private string GetFromXPath(string XML, string XPath)
    {
        if (XML.Trim() == "")
            return "";

        string Result = "";
        try
        {
            XPathDocument doc = new XPathDocument(new StringReader(XML));
            XPathNavigator nav = doc.CreateNavigator();
            XPathNodeIterator nodes = nav.Select(XPath);
            while (nodes.MoveNext())
                Result += nodes.Current.Value;
        }
        catch//(Exception ee)
        {
            return "";
            //return ee.Message;
        }

        return Result;
    }
コード例 #59
0
		public string Execute()
		{
			XPathDocument document = new XPathDocument(_xmlFileName);
			XPathNavigator navigator = document.CreateNavigator();
			XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);

			if (!string.IsNullOrEmpty(_prefix) && !string.IsNullOrEmpty(_namespace))
			{
				manager.AddNamespace(_prefix, _namespace);
			}

			XPathExpression expression = XPathExpression.Compile(_xpath, manager);
			switch (expression.ReturnType)
			{
				case XPathResultType.Number:
				case XPathResultType.Boolean:
				case XPathResultType.String:
					_value = navigator.Evaluate(expression).ToString();
					break;
				case XPathResultType.NodeSet:
					XPathNodeIterator nodes = navigator.Select(expression);


					StringBuilder builder = new StringBuilder();
					while (nodes.MoveNext())
						builder.AppendFormat("{0};", nodes.Current.Value);

					if (builder.Length > 0)
						builder.Remove(builder.Length - 1, 1);

					_value = builder.ToString();

					break;
			}
			return Value;
		}
コード例 #60
-1
ファイル: Login.aspx.cs プロジェクト: aptivasoft/Adio
    public void renderLoginControls()
    {
        try
        {
            string XmlPath = Server.MapPath("xml/UserLogin.xml");
            string XsltPath = Server.MapPath("xslt/UserLogin.xslt");

            XPathDocument xdoc = new XPathDocument(XmlPath);

            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(XsltPath);

            StringWriter sw = new StringWriter();

            //Transform
            transform.Transform(xdoc, null, sw);
            string result = sw.ToString();

            //Remove Namespace
            result = result.Replace("xmlns:asp=\"remove\"", "");
            result = result.Replace("xmlns:cc1=\"remove\"", "");

            //Parse Control
            Control ctrl = Page.ParseControl(result);
            phLogin.Controls.Add(ctrl);
        }
        catch (Exception ex)
        {
            objNLog.Error("Error : " + ex.Message);
        }
    }