Example #1
1
  protected void GenerateAction_Click(object sender, EventArgs e)
  {
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(Resources.MyResourceStrings.MyDocument);

    XmlNode TextNode;
    XmlNamespaceManager NsMgr = new XmlNamespaceManager(doc.NameTable);
    NsMgr.AddNamespace("ns1", "uri:AspNetPro20/Chapter16/Demo1");
    NsMgr.AddNamespace("w", "http://schemas.microsoft.com/office/word/2003/wordml");

    TextNode = doc.SelectSingleNode("//ns1:Firstname//w:p", NsMgr);
    TextNode.InnerXml = string.Format("<w:r><w:t>{0}</w:t></w:r>", TextFirstname.Text);

    TextNode = doc.SelectSingleNode("//ns1:Lastname//w:p", NsMgr);
    TextNode.InnerXml = string.Format("<w:r><w:t>{0}</w:t></w:r>", TextLastname.Text);

    TextNode = doc.SelectSingleNode("//ns1:Age//w:p", NsMgr);
    TextNode.InnerXml = string.Format("<w:r><w:t>{0}</w:t></w:r>", TextAge.Text);

    // Clear the response
    Response.Clear();
    Response.ContentType = "application/msword";
    Response.Write(doc.OuterXml);
    Response.End();
  }
Example #2
1
    public void SaveStatistik(string statText, string name)
    {
        CheckFile ();
        // Создаем корневой элемент
        XmlDocument xmlDoc = new XmlDocument ();
        if(File.Exists(filePatch))
            xmlDoc.Load (filePatch);

        XmlNode xRoot;
        XmlNode findNode = xmlDoc.SelectSingleNode ("Stats"); // найти корневой элемент
        if ( findNode == null)
            xRoot = xmlDoc.CreateElement ("Stats"); 	// Создать корневой элемент
        else
            xRoot = findNode;

        xmlDoc.AppendChild (xRoot);

        //Временные преременные для дочерних элементов и атрибутов
        XmlElement taskElement1; //Элемент 1-го уровня

        findNode = xmlDoc.SelectSingleNode ("Stats/" + name);
        if ( findNode == null) {
            taskElement1 = xmlDoc.CreateElement (name);
            taskElement1.InnerText = statText;
            xRoot.AppendChild (taskElement1);
        } else {
            findNode.InnerText = statText;
        }

        /////////////////////////////////////////////////////////////
        xmlDoc.Save ("Data/Save/Stats.xml");
    }
Example #3
1
    public void SaveStatistik(Vector3 vec3)
    {
        string name = "Position";

        CheckFile ();
        // Создаем корневой элемент
        XmlDocument xmlDoc = new XmlDocument ();
        if(File.Exists(filePatch))
            xmlDoc.Load (filePatch);

        XmlNode xRoot;
        XmlNode findNode = xmlDoc.SelectSingleNode ("Stats"); // найти корневой элемент
        if ( findNode == null)
            xRoot = xmlDoc.CreateElement ("Stats"); 	// Создать корневой элемент
        else
            xRoot = findNode;

        xmlDoc.AppendChild (xRoot);

        //Временные преременные для дочерних элементов и атрибутов
        XmlElement taskElement1; //Элемент 1-го уровня
        XmlAttribute posAtr;

        findNode = xmlDoc.SelectSingleNode ("Stats/" + name);
        if (findNode == null) {
            taskElement1 = xmlDoc.CreateElement (name);

            posAtr = xmlDoc.CreateAttribute ("z");
            posAtr.Value = vec3.z.ToString ();
            taskElement1.Attributes.Append (posAtr);

            posAtr = xmlDoc.CreateAttribute ("y");
            posAtr.Value = vec3.y.ToString ();
            taskElement1.Attributes.Append (posAtr);

            posAtr = xmlDoc.CreateAttribute ("x");
            posAtr.Value = vec3.x.ToString ();
            taskElement1.Attributes.Append (posAtr);

            xRoot.AppendChild (taskElement1);
        }
        else
        {
            findNode.Attributes["x"].Value = vec3.x.ToString ();

            findNode.Attributes["y"].Value = vec3.y.ToString ();
        }

        xmlDoc.Save ("Data/Save/Stats.xml");
    }
Example #4
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        string index = Label2.Text;
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(Server.MapPath("~/" + "ad.xml"));
        XmlNode root = xmlDoc.SelectSingleNode("ttt");
        XmlNodeList xnl = xmlDoc.SelectSingleNode("ttt").ChildNodes;
        for (int i = 0; i < xnl.Count; i++)
        {
            XmlElement xe = (XmlElement)xnl.Item(i);
            if (xe.GetAttribute("index") == index)
            {
                xe.SetAttribute("src", TextBox1.Text);
                xe.SetAttribute("href",TextBox4.Text);
                xe.SetAttribute("target", TextBox5.Text);
            }

        }

        //root.PrependChild(xe);

        xmlDoc.Save(Server.MapPath("~/" + "ad.xml"));

        msg("更新flash成功了");
        return;
        Response.Redirect("adselect.aspx");
    }
Example #5
0
 protected void parseProfile(string XML)
 {
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.LoadXml(XML);
     gold = int.Parse (xmlDoc.SelectSingleNode ("player/gold").InnerText);
     cash = int.Parse (xmlDoc.SelectSingleNode ("player/cash").InnerText);
 }
 public Collection<Rss.Items> GetFeed()
 {
     if (String.IsNullOrEmpty(Url))
       throw new ArgumentException("Bir Rss adresi belirtmelisiniz");
       try
       {
       using (XmlReader reader = XmlReader.Create(Url))
       {
       XmlDocument xmlDoc = new XmlDocument();
       try
       {
           xmlDoc.Load(reader);
       }
       catch
       {
           MessageBox.Show("Baþvurulan adreste bir söz dizimi hatasý var.\nSite yöneticilerine haber verin.");
       }
       ParseDocElements(xmlDoc.SelectSingleNode("//channel"), "title", ref _feedTitle);
       ParseDocElements(xmlDoc.SelectSingleNode("//channel"), "description", ref _feedDescription);
       ParseRssItems(xmlDoc);
       return _rssItems;
       }
       }
       catch
       {
       MessageBox.Show("Servis þu anda hizmet vermiyor");
       return _rssItems;
       }
 }
Example #7
0
 private string Module_Action_Delete()
 {
     string tmpstr = "";
     string trootstr = cls.getSafeString(encode.base64.decodeBase64(request.querystring("root")));
     string tvaluestr = cls.getSafeString(encode.base64.decodeBase64(request.querystring("value")));
     if (com.fileExists(Server.MapPath(trootstr)))
     {
       try
       {
     string tnode, tfield, tbase;
     XmlDocument tXMLDom = new XmlDocument();
     tXMLDom.Load(Server.MapPath(trootstr));
     XmlNode tXmlNode = tXMLDom.SelectSingleNode("/xml/configure");
     tnode = tXmlNode.ChildNodes.Item(0).InnerText;
     tfield = tXmlNode.ChildNodes.Item(1).InnerText;
     tbase = tXmlNode.ChildNodes.Item(2).InnerText;
     XmlNode tXmlNodeDel = tXMLDom.SelectSingleNode("/xml/" + tbase + "/" + tnode + "[" + cls.getLRStr(tfield, ",", "left") + "='" + tvaluestr + "']");
     if (tXmlNodeDel != null)
     {
       tXmlNodeDel.ParentNode.RemoveChild(tXmlNodeDel);
       tXMLDom.Save(Server.MapPath(trootstr));
     }
     tmpstr = jt.itake("global.lng_common.delete-succeed", "lng");
       }
       catch
       {
     tmpstr = jt.itake("global.lng_common.delete-failed", "lng");
       }
     }
     else tmpstr = jt.itake("global.lng_common.delete-failed", "lng");
     tmpstr = config.ajaxPreContent + tmpstr;
     return tmpstr;
 }
Example #8
0
        private static string ParseXmlToCreateFullName(XmlDocument xml)
        {
            var title = xml?.SelectSingleNode("//user/results/name/title")?.InnerText;
            var first = xml?.SelectSingleNode("//user/results/name/first")?.InnerText;
            var last  = xml?.SelectSingleNode("//user/results/name/last")?.InnerText;

            return($"{title} {first} {last}");
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            this.Response.Write("<script language=\"javascript\">");
            this.Response.Write("alert('您未正常登录,请登录后再使用,谢谢!')");
            this.Response.Write("</script>");
            this.Response.Redirect("index.htm");
        }
        string strcn = DataAccRes.DefaultDataConnInfo.Value;
        SqlConnection CN = new SqlConnection(strcn);
        XmlDocument xmldoc = new XmlDocument();
        //读取用户参数
        StreamReader streamreader = new StreamReader(this.Request.InputStream, Encoding.UTF8);
        xmldoc.LoadXml(streamreader.ReadToEnd());
        if (xmldoc == null) return;
        string strcmd = xmldoc.SelectSingleNode("//all/command").InnerText;
        string strdata = xmldoc.SelectSingleNode("//all/data").InnerText;
        string xmlstr = "";
        switch (strcmd)
        {
            case "pwd":
                User user = new User(this.Session["userid"].ToString());
                string oldpwd = basefun.valtag(strdata,"pwdold");
                if (this.Session["userkey"].ToString() != oldpwd)
                {
                    xmlstr = "<table><result>原密码不正确!</result></table>";
                    break;
                }
                string newpwd = basefun.valtag(strdata, "pwdnew");
                bool bModify = user.ModifyPassword(oldpwd, newpwd);
                if (!bModify)
                {
                    xmlstr = "<table><result>修改失败!</result></table>";
                }
                else
                {
                    xmlstr = "<table><result>修改成功!</result></table>";
                }
         
                break;
            case "querydb":
                string systemdb = DataAccRes.AppSettings("SystemDB");
                xmlstr = "<table><svr>" + CN.DataSource + "</svr><userdb>" + CN.Database + "</userdb><sysdb>" + systemdb + "</sysdb></table>";
                break;
            case "updatedb":
                WriteWebConfig(strdata);
                xmlstr = "<table><result>修改成功!</result></table>";
                break;
        }

        Response.ContentType = "text/xml";
        Response.Expires = -1;
        Response.Clear();
        Response.Write("<?xml version='1.0' encoding='GB2312'?>");
        Response.Write(xmlstr);
        //Response.End();
    }
Example #10
0
    // 客户信息查询接口 lihongtu
    public static Int32 QueryCustInfo(String ProductNo, out CustInfo custinfo, out String ErrMsg)
    {
        Int32 Result = ErrorDefinition.CIP_IError_Result_UnknowError_Code;
        ErrMsg = ErrorDefinition.CIP_IError_Result_UnknowError_Msg;
        String TransactionID = CreateTransactionID();
        StringBuilder requestXml = new StringBuilder();
        String responseXml = String.Empty;
        custinfo = new CustInfo();
        try
        {
            #region 拼接请求xml字符串
            //100101	客户查询
            requestXml.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            requestXml.Append("<PayPlatRequestParameter>");
            requestXml.Append("<CTRL-INFO WEBSVRNAME=\"客户查询\" WEBSVRCODE=\"100101\" APPFROM=\"100101|310000-TEST1-127.0.0.1|1.0|127.0.0.1\" KEEP=\"" + TransactionID + "\" />");
            requestXml.Append("<PARAMETERS>");

            //添加参数

            requestXml.AppendFormat("<PRODUCTNO>{0}</PRODUCTNO>", "yy" + ProductNo);
            requestXml.AppendFormat("<ACCEPTORGCODE>{0}</ACCEPTORGCODE>", BesttoneAccountConstDefinition.DefaultInstance.ACCEPTORGCODE);  //002310000000000
            requestXml.AppendFormat("<ACCEPTSEQNO>{0}</ACCEPTSEQNO>", TransactionID);
            requestXml.AppendFormat("<INPUTTIME>{0}</INPUTTIME>", DateTime.Now.ToString("yyyyMMddHHmmss"));

            requestXml.Append("</PARAMETERS>");
            requestXml.Append("</PayPlatRequestParameter>");

            #endregion

            //请求接口

            responseXml = serviceProxy.dispatchCommand("100101|310000-TEST1-127.0.0.1|1.0|127.0.0.1", requestXml.ToString());

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(responseXml);

            String responseCode = xmlDoc.SelectSingleNode("/PayPlatResponseParameter/RESPONSECODE").InnerText;
            ErrMsg = xmlDoc.SelectSingleNode("/PayPlatResponseParameter/RESPONSECONTENT").InnerText;

            if (responseCode == "000000")
            {
                XmlNode dataNode = xmlDoc.SelectNodes("/PayPlatResponseParameter/RESULTDATESET/DATAS")[0];
                custinfo.CustomerNo = dataNode.Attributes["CUSTOMER_NO"].Value;
                custinfo.ProductNo = dataNode.Attributes["PRODUCT_NO"].Value;
                custinfo.CustomerName = dataNode.Attributes["CUSTOMER_NAME"].Value;
                custinfo.IdType = dataNode.Attributes["ID_TYPE"].Value;
                custinfo.IdNo = dataNode.Attributes["ID_NO"].Value;
                Result = 0;
                ErrMsg = String.Empty;
            }

        }
        catch (System.Exception ex)
        {

        }
        return Result;
    }
Example #11
0
    protected void Page_Load (object sender, EventArgs e)
    {
        if (Request.QueryString["ticket"] != null && hTicket.Value == "")
        {
            //this is the callback
            this.hTicket.Value = Request.QueryString["ticket"].ToString();
            LoginPanel.Visible = false;

           HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://pirateweb.net/Pages/Security/ValidateTicket.aspx?ticket=" + Request.QueryString["ticket"].ToString());

             //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:2900/Pages/Security/ValidateTicket.aspx?ticket=" + Request.QueryString["ticket"].ToString());
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string tmp = reader.ReadToEnd();
            response.Close();

            Response.ContentType = "text/xml";
            Response.Clear();
            Response.Write(tmp);
            Response.End();

            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(tmp);
            ResultPanel.Visible = true;
            resultdiv.InnerHtml = "";
            if (xdoc.SelectSingleNode("//USER") != null)
            {
                resultdiv.InnerHtml += xdoc.SelectSingleNode("//USER/ID").InnerText;
                resultdiv.InnerHtml += "<BR>";
                resultdiv.InnerHtml += xdoc.SelectSingleNode("//USER/NAME").InnerText;
                resultdiv.InnerHtml += "<BR>";
                resultdiv.InnerHtml += xdoc.SelectSingleNode("//USER/GEOGRAPHIESFORPERSON/GEOGRAPHY").Attributes["name"];
                resultdiv.InnerHtml += "<BR>";
            }
            else
            {
                resultdiv.InnerHtml=xdoc.InnerText;
            }
        }
        else if (this.hTicket.Value != "")
        {
            //the callback has been done we are running normally logged in

        }
        else
        {
            // prepare for login
            LoginPanel.Visible = true;
        }
    }
Example #12
0
    //.Load("Assets/Scripts/SaveGame.xml")
    ////---For encrypted one---
    ////Read in SaveGame.xml
    //XmlDocument SaveGameDoc = new XmlDocument();
    //SaveGameDoc.LoadXml(DoSaveGame.FetchSaveData());
    ////---For encrypted one---
    ////Save XML
    //DoSaveGame.UpdateSaveData(SaveGameDoc);
    //.LoadXml(Resources.Load("Defult Save/DefultSaveGame.xml").ToString()
    //.LoadXml(Resources.Load("CutScenes/CutSceneEvents.xml").ToString()
    //.LoadXml(Resources.Load("ItemFile/Items.xml").ToString()
    public static void NewGame()
    {
        //Read in DefultSaveGame.xml
        XmlDocument DefultSaveGameDoc = new XmlDocument();
        DefultSaveGameDoc.LoadXml(Resources.Load("Defult Save/DefultSaveGame").ToString());

        //Getting GameVersion and inputting it into SaveGameData
        StreamReader SR = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "/Delirium/Version.txt");
        DefultSaveGameDoc.SelectSingleNode("SaveData/Settings/GameVersion").InnerText = SR.ReadLine();
        DefultSaveGameDoc.SelectSingleNode("SaveData/Settings/DateTimeStarted").InnerText = System.DateTime.Now.ToString();
        SR.Close();

        //Update/Save Data
        UpdateSaveData(DefultSaveGameDoc);
    }
Example #13
0
    public Cartelera getCartelCine()
    {
        doc = new XmlDocument();
        try
        {
            doc.Load("http://www.cinepolis.com.mx/iphone/xml-iphone.aspx?query=cartelera&ci=" + cartel.CiudadID);
        }
        catch (Exception e) { return null; }

        try
        {
            complejoInfo = doc.SelectSingleNode("//Cartelera//Complejo[@Complejoid='" + cartel.ComplejoID + "']");
            cartel.Complejo = complejoInfo.Attributes.GetNamedItem("Nombre").Value;
            cartel.Latitud = complejoInfo.ChildNodes[1].InnerText.Trim();
            cartel.Longitud = complejoInfo.ChildNodes[2].InnerText.Trim();

            Complejos_peli = doc.SelectNodes("//Cartelera//Complejo[@Complejoid='" + cartel.ComplejoID + "']/Pelicula");
            foreach (XmlNode complejo_peli in Complejos_peli)
            {
                peli = new Pelicula();
                string Horario_Peli = "";
                peli.PeliculaID = complejo_peli.FirstChild.InnerText;

                Complejos_hora = doc.SelectNodes("//Cartelera//Complejo/Pelicula[Peliculaid='" + peli.PeliculaID + "']/Horarios/Horario");
                foreach (XmlNode horario in Complejos_hora)
                {
                    Horario_Peli += horario.InnerText + " - ";
                }

                peliculaInfo = doc.SelectSingleNode("//Peliculas//Pelicula[@Peliculaid='" + peli.PeliculaID + "']");

                peli.Nombre = peliculaInfo.Attributes.GetNamedItem("Nombre").Value;
                peli.Clasificacion = peliculaInfo.ChildNodes[1].InnerText;
                peli.Calificacion = peliculaInfo.ChildNodes[4].InnerText;
                peli.Descripcion = peliculaInfo.ChildNodes[6].InnerText;
                peli.Director = peliculaInfo.ChildNodes[7].InnerText;
                peli.Actor = peliculaInfo.ChildNodes[8].InnerText;
                peli.Duracion = peliculaInfo.ChildNodes[16].InnerText;
                peli.Trailer = peliculaInfo.ChildNodes[19].InnerText;
                peli.Horarios = Horario_Peli;

                cartel.Peliculas.Add(peli);

            }
        }
        catch (Exception e) { return null;}
        return cartel;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string id = Request.QueryString["id"], xpathExpr;
        int counter = 0;

        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("../Xml/Playlists.xml"));

        if (id != "0")
        {
            xpathExpr = "/playlists/playlist[id='" + id + "']";
            XmlNode node_id = doc.SelectSingleNode(xpathExpr);

            Response.Write("{ \"id\": \"" + node_id.ChildNodes[0].InnerText.Trim() + "\", \"title\": \"" + node_id.ChildNodes[1].InnerText.Trim() + "\", \"songs\": ");

            Response.Write("[");
            foreach (XmlNode node in node_id.ChildNodes[2])
            {
                Response.Write("{ \"id\": \"" + node.ChildNodes[0].InnerText.Trim() + "\" }");

                counter++;
                if (counter < node_id.ChildNodes[2].ChildNodes.Count) Response.Write(", ");
            }
            Response.Write("] }");
        }
    }
Example #15
0
    /// <summary>
    /// 删除XmlNode属性
    /// 使用示列:
    /// XmlHelper.DeleteAttribute(path, nodeName, "");
    /// XmlHelper.DeleteAttribute(path, nodeName, attributeName,attributeValue);
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <param name="nodeName">节点名称</param>
    /// <param name="attributeName">属性名称</param>
    /// <returns>void</returns>
    public static void DeleteAttribute(string path, string nodeName, string attributeName)
    {
        if (attributeName.Equals(""))
        {
            return;
        }

        try
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(path);

            XmlElement element = doc.SelectSingleNode(nodeName) as XmlElement;
            if (element == null)
            {
                throw new Exception("节点元素不存在!");
            }
            else
            {
                element.RemoveAttribute(attributeName);
                doc.Save(path);
            }
        }
        catch
        { }
    }
 protected void Button1_ServerClick(object sender, EventArgs e)
 {
     try
     {
         string currency = idChoice.Value;
         XmlDocument doc = new XmlDocument();
         string url = Server.MapPath("../data/xml/configproduct.xml");
         XmlTextReader reader = new XmlTextReader(url);
         doc.Load(reader);
         reader.Close();
         if (doc.IsReadOnly)
         {
             diverr.Visible = true;
             diverr.InnerHtml = "File XML đã bị khóa. Không thể thay đổi";
             return;
         }
         XmlNode nodeEdit = doc.SelectSingleNode("root/product[nameappunit='currency']/unit");
         string value = nodeEdit.InnerText;
         if (!value.Equals(currency))
         {
             nodeEdit.InnerText = currency;
             doc.Save(url);
             Application["currency"] = currency;
             diverr.Visible = true;
             diverr.InnerHtml = "Đã thay đổi cách hiển thị tiền tệ";
         }
         else
         {
             diverr.Visible = true;
             diverr.InnerHtml = "Hệ thống đang hiển thị kiểu tiền này.";
         }
     }catch
     {}
 }
Example #17
0
        protected virtual void ParseLinkAttributes(string link)
        {
            Assert.ArgumentNotNull(link, "link");
            XmlDocument xmlDocument = XmlUtil.LoadXml(link);

            XmlNode node = xmlDocument?.SelectSingleNode("/link");

            if (node == null)
            {
                return;
            }

            this.AnalyticsLinkAttributes[Attributes.goalid]  = XmlUtil.GetAttribute(Attributes.goalid, node);
            this.AnalyticsLinkAttributes[Attributes.eventid] = XmlUtil.GetAttribute(Attributes.eventid, node);

            this.AnalyticsLinkAttributes[Attributes.anchor]      = XmlUtil.GetAttribute(Attributes.anchor, node);
            this.AnalyticsLinkAttributes[Attributes._class]      = XmlUtil.GetAttribute(Attributes._class, node);
            this.AnalyticsLinkAttributes[Attributes.id]          = XmlUtil.GetAttribute(Attributes.id, node);
            this.AnalyticsLinkAttributes[Attributes.linktype]    = XmlUtil.GetAttribute(Attributes.linktype, node);
            this.AnalyticsLinkAttributes[Attributes.querystring] = XmlUtil.GetAttribute(Attributes.querystring, node);
            this.AnalyticsLinkAttributes[Attributes.target]      = XmlUtil.GetAttribute(Attributes.target, node);
            this.AnalyticsLinkAttributes[Attributes.text]        = XmlUtil.GetAttribute(Attributes.text, node);
            this.AnalyticsLinkAttributes[Attributes.title]       = XmlUtil.GetAttribute(Attributes.title, node);
            this.AnalyticsLinkAttributes[Attributes.url]         = XmlUtil.GetAttribute(Attributes.url, node);
        }
Example #18
0
    public float[,] LoadFloatArrFromXML(string fileName, int col, int row)
    {
        float[, ] resultArr = new float[col, row];

        string xmlStr = Resources.Load ("Data/" + fileName).ToString ();

        XmlDocument xml = new XmlDocument ();

        xml.LoadXml (xmlStr);

        XmlNodeList xmlNodeList = xml.SelectSingleNode ("data").ChildNodes;
        int i = 0, j;
        foreach (XmlElement xmlE in xmlNodeList)
        {
            j = 0;
            foreach (XmlElement xmlEE in xmlE)
            {
                resultArr[i, j] = float.Parse (xmlEE.InnerText);
                j++;
            }
            i++;
        }

        return resultArr;
    }
	private static void postProcessWP8Build(string pathToBuiltProject) {
		string manifestFilePath = Path.Combine( Path.Combine (pathToBuiltProject, PlayerSettings.productName), "Properties/WMAppManifest.xml");

		if (!File.Exists (manifestFilePath)) {
			UnityEngine.Debug.LogError ("Windows Phone manifest not found: " + manifestFilePath);
			return;
		}

		XmlDocument manifest = new XmlDocument ();
		manifest.Load(manifestFilePath);

		XmlNode capabilities = manifest.SelectSingleNode ("//Capabilities");
		XmlNodeList matchingCapability = manifest.SelectNodes("//Capability[@Name='ID_CAP_IDENTITY_DEVICE']");
		if (matchingCapability.Count == 0) {
			XmlElement newCapability = manifest.CreateElement("Capability");
			newCapability.SetAttribute("Name", "ID_CAP_IDENTITY_DEVICE");
			capabilities.AppendChild(newCapability);
		}

		matchingCapability = manifest.SelectNodes("//Capability[@Name='ID_CAP_PUSH_NOTIFICATION']");
		if (matchingCapability.Count == 0) {
			XmlElement newCapability = manifest.CreateElement("Capability");
			newCapability.SetAttribute("Name", "ID_CAP_PUSH_NOTIFICATION");
			capabilities.AppendChild(newCapability);
		}

		manifest.Save (manifestFilePath);

		UnityEngine.Debug.Log ("Windows Phone manifest sucessfully patched");
	}
Example #20
0
    public void AddXml()
    {
        string filepath = Application.dataPath + @"/my.xml";
        if(File.Exists (filepath))
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filepath);
            XmlNode root = xmlDoc.SelectSingleNode("transforms");
            XmlElement elmNew = xmlDoc.CreateElement("rotation");
            elmNew.SetAttribute("id","1");
         		    elmNew.SetAttribute("name","yusong");

             XmlElement rotation_X = xmlDoc.CreateElement("x");
             rotation_X.InnerText = "0";
             rotation_X.SetAttribute("id","1");
             XmlElement rotation_Y = xmlDoc.CreateElement("y");
             rotation_Y.InnerText = "1";
             XmlElement rotation_Z = xmlDoc.CreateElement("z");
             rotation_Z.InnerText = "2";

             elmNew.AppendChild(rotation_X);
             elmNew.AppendChild(rotation_Y);
             elmNew.AppendChild(rotation_Z);
             root.AppendChild(elmNew);
             xmlDoc.AppendChild(root);
             xmlDoc.Save(filepath);
             Debug.Log("AddXml OK!");
        }
    }
Example #21
0
    public void Load()
    {
        xmldoc = new XmlDocument();

        xmldoc.Load("Config.xml");
        root = xmldoc.SelectSingleNode("XML");
    }
    /// <summary>
    /// Converts the route obtained by OnlineMapsFindDirection, a list of the steps of the route.
    /// </summary>
    /// <param name="route">Route obtained by OnlineMapsFindDirection.</param>
    /// <returns>List of OnlineMapsDirectionStep or null.</returns>
    public static List<OnlineMapsDirectionStep> TryParse(string route)
    {
        try
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(route);

            XmlNode direction = doc.SelectSingleNode("//DirectionsResponse");
            if (direction == null) return null;

            XmlNode status = direction.SelectSingleNode("status");
            if (status == null || status.InnerText != "OK") return null;

            XmlNode legNode = direction.SelectSingleNode("route/leg");
            if (legNode == null) return null;

            XmlNodeList stepNodes = legNode.SelectNodes("step");
            if (stepNodes == null) return null;

            List<OnlineMapsDirectionStep> steps = new List<OnlineMapsDirectionStep>();

            foreach (XmlNode step in stepNodes)
            {
                OnlineMapsDirectionStep navigationStep = new OnlineMapsDirectionStep(step);
                steps.Add(navigationStep);
            }

            return steps;
        }
        catch { }

        return null;
    }
Example #23
0
 public static string BitlyShortLink(string longLink)
 {
     string bitlyResponse = ExecuteGetCommand(string.Format(bitlyUrl, longLink));
     XmlDocument doc = new XmlDocument();
     doc.LoadXml(bitlyResponse);
     return doc.SelectSingleNode("//url").InnerText;
 }
        internal static void SelectForEachFromValues(List <ForEachItem> parameterSetSources, ref XmlDocument values,
                                                     Dictionary <string, ParameterInfo> globalParamSets, object parentExitData)
        {
            foreach (ForEachItem fe in parameterSetSources)
            {
                ParameterSourceInfo pss = fe.ParameterSource;

                XmlDocument v   = pss.HasName ? GetParamSet(pss.Name, globalParamSets, pss.IsNameParentExitData, parentExitData) : values;
                XmlNode     src = v?.SelectSingleNode(pss.Source);
                if (src != null)
                {
                    if (src.NodeType == XmlNodeType.Element)
                    {
                        XmlNodeList nodes = src.SelectNodes("*");
                        if (nodes.Count > 0)
                        {
                            foreach (XmlNode node in nodes)
                            {
                                fe.Values.Add(node.InnerXml);   //InnerText or just the node?
                            }
                        }
                        else
                        {
                            fe.Values.Add(src.InnerText);
                        }
                    }
                    else
                    {
                        fe.Values.Add(src.Value);
                    }
                }
            }
        }
    public static AEAnimationData ParceAnimationData(string data)
    {
        XmlDocument doc =  new XmlDocument();
        doc.LoadXml(data);

        AEAnimationData animation = new AEAnimationData ();

        XmlNode anim = doc.SelectSingleNode("after_affect_animation_doc");

        XmlNode meta = anim.SelectSingleNode("meta");
        animation.frameDuration = GetFloat (meta, "frameDuration");
        animation.totalFrames = GetInt (meta, "totalFrames");
        animation.duration =  GetFloat (meta, "duration");

        frameDuration = animation.frameDuration;

        XmlNode composition = anim.SelectSingleNode("composition");
        animation.composition = ParseComposition (composition);

        XmlNode sub_items = anim.SelectSingleNode("sub_items");
        XmlNodeList usedCompositions = sub_items.SelectNodes("composition");

        foreach (XmlNode c in usedCompositions) {
            animation.addComposition(ParseComposition (c));
        }

        return animation;
    }
Example #26
0
    /* This method extracts the data from the temporary XML object and places it
     * in runtime movement object that will be processed on the spot.
    */
    IEnumerator ExtractMovement(XmlDocument xml)
    {
        Movement movement;

        //Set the name of the test being run in the global variable
        gs.setTestName(xml.SelectSingleNode("Test/Name").InnerText);

        //Move through each tagged item within the xml document
        foreach (XmlNode node in xml.SelectNodes("Test/Movement")){
            movement = new Movement();

            //Extract and assign tagged items within the xmlDoc to object variables within Movement class
            movement.MovementID = node.SelectSingleNode("MovementId").InnerText;
            movement.MovementDesc = node.SelectSingleNode("MovementDesc").InnerText;

            //Assign MovementDetails to Movement Class variables
            foreach (XmlNode detail in node.SelectNodes("MovementDetail")){
                movement.Sequence = detail.SelectSingleNode("SequenceId").InnerText;
                movement.Path = detail.SelectSingleNode("Path").InnerText;
                movement.PathDesc = detail.SelectSingleNode("PathDesc").InnerText;
                movement.Gait = detail.SelectSingleNode("Gait").InnerText;

                //Call LoadMovement Coroutine method and pass movement object
                //and wait for the finish of Coroutine to process further information.
                yield return StartCoroutine(ProcessMovement(movement));
            }
        }
    }
Example #27
0
 static void SimpleSearch()
 {
     XmlDocument doc = new XmlDocument();
     doc.Load(Bookstore.Data.Settings.Default.simpleSearchFile);
     XmlNode query = doc.SelectSingleNode("/query");
     string title = DataImporter.GetValue(query, "title");
     string author = DataImporter.GetValue(query, "author");
     string isbn = DataImporter.GetValue(query, "isbn");
     BookstoreEntities context = new BookstoreEntities();
     using (context)
     {
         IList<Book> found = BookstoreDAL.FindBook(title, author, isbn, context);
         if (found.Count > 0)
         {
             Console.WriteLine("{0} books found:", found.Count);
             foreach (var book in found)
             {
                 if (book.Reviews.Count > 0)
                 {
                     Console.WriteLine("{0} --> {1} reviews", book.Title, book.Reviews.Count);
                 }
                 else
                 {
                     Console.WriteLine("{0} --> no reviews", book.Title);
                 }
             }
         }
         else
         {
             Console.WriteLine("Nothing found");
         }
     }
 }
Example #28
0
	public static void Main(string[] arg) {
		if (arg.Length < 1) throw new ArgumentException("Must pass one or two command line arguments.");
	
		StringWriter sw = new StringWriter();
		string s;
		while ((s = Console.ReadLine()) != null) {
			sw.WriteLine(s);
		}
		
		XmlDocument d = new XmlDocument();
		d.LoadXml(sw.ToString());
		
		object ret;
		
		if (arg.Length == 1) {
			ret = d.CreateNavigator().Evaluate(arg[0]);
		} else if (arg.Length == 2 && arg[0] == "-expr") {
			ret = d.CreateNavigator().Evaluate(arg[1]);
		} else if (arg.Length == 2 && arg[0] == "-node") {
			ret = d.SelectSingleNode(arg[1]);
		} else {
			throw new ArgumentException("Bad command line arguments.");
		}
		
		if (ret is XPathNodeIterator) {
			XPathNodeIterator iter = (XPathNodeIterator)ret;
			while (iter.MoveNext()) {
				Console.WriteLine(iter.Current);
			}
		} else if (ret is XmlNode) {
			Console.WriteLine(((XmlNode)ret).InnerXml);
		} else {
			Console.WriteLine(ret);
		}
	}
Example #29
0
    //导入数据库
    protected void btnImportData_Click(object sender, EventArgs e)
    {
        string xml = txtData.Value.Trim();
        if (string.IsNullOrEmpty(xml))
        {
            Common.MessageBox.Show(this, "文本框为空!");
            return;
        }
        try
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml); //加载XML文档

            XmlNode root = xmlDoc.SelectSingleNode("//config");
            InsertTableData(xmlDoc, "webconfig");
            InsertTableData(xmlDoc, "dictionary");
            InsertTableData(xmlDoc, "channel");
            InsertTableData(xmlDoc, "ad");
            InsertTableData(xmlDoc, "adtype");
            Common.MessageBox.Show(this, "成功导入数据库!");
        }
        catch (Exception ex)
        {
            Common.MessageBox.Show(this, ex.Message);
        }
    }
Example #30
0
 /// <summary>
 /// upload image and get task's id</summary>
 /// <param name="data"> byte[], image of document</param>
 /// <returns> returns UrlData with URL (empty in case of failure) and Status of operation)</returns>
 public async Task<string> PostImage(byte[] data)
 {
     var client = new HttpClient();
     setAuthentication(client);
     string id = "";
     client.BaseAddress = new Uri("http://cloud.ocrsdk.com/processMRZ");
     try
     {
         var response = await client.PostAsync(client.BaseAddress, new ByteArrayContent(data));
         response.EnsureSuccessStatusCode();
         //Console.WriteLine(response.StatusCode);
         ///response.isStatusCode != ... )
         var result = await response.Content.ReadAsStringAsync();
         XmlDocument doc = new XmlDocument();
         doc.LoadXml(result);
         id = doc.SelectSingleNode("/response/task/@id").Value;
     }
     catch (Exception exception)
     {
         //Console.WriteLine("CAUGHT EXCEPTION:");
         //Console.WriteLine(exception);
         return "";
     }
     return id;
 }
Example #31
0
        /// <summary>
        /// Print the object's XML to the XmlWriter.
        /// </summary>
        /// <param name="objWriter">XmlTextWriter to write with.</param>
        public void Print(XmlTextWriter objWriter, CultureInfo objCulture, string strLanguageToPrint)
        {
            if (!_blnPrint)
            {
                return;
            }
            objWriter.WriteStartElement("quality");
            objWriter.WriteElementString("name", DisplayNameShort(strLanguageToPrint));
            objWriter.WriteElementString("formattedname", FormattedDisplayName(objCulture, strLanguageToPrint));
            objWriter.WriteElementString("extra", LanguageManager.TranslateExtra(_strExtra, strLanguageToPrint));
            objWriter.WriteElementString("lp", _intLP.ToString(objCulture));
            objWriter.WriteElementString("cost", Cost.ToString(_objCharacter.Options.NuyenFormat, objCulture));
            string strLifestyleQualityType = _objLifestyleQualityType.ToString();

            if (strLanguageToPrint != GlobalOptions.DefaultLanguage)
            {
                XmlDocument objXmlDocument = XmlManager.Load("lifestyles.xml", strLanguageToPrint);

                XmlNode objNode = objXmlDocument?.SelectSingleNode("/chummer/categories/category[. = \"" + strLifestyleQualityType + "\"]");
                strLifestyleQualityType = objNode?.Attributes?["translate"]?.InnerText ?? strLifestyleQualityType;
            }
            objWriter.WriteElementString("lifestylequalitytype", strLifestyleQualityType);
            objWriter.WriteElementString("lifestylequalitytype_english", _objLifestyleQualityType.ToString());
            objWriter.WriteElementString("lifestylequalitysource", _objLifestyleQualitySource.ToString());
            objWriter.WriteElementString("source", CommonFunctions.LanguageBookShort(Source, strLanguageToPrint));
            objWriter.WriteElementString("page", Page(strLanguageToPrint));
            if (_objCharacter.Options.PrintNotes)
            {
                objWriter.WriteElementString("notes", _strNotes);
            }
            objWriter.WriteEndElement();
        }
Example #32
0
    public static bool IsDotNetProject(this XmlDocument csproj)
    {
        var project = csproj?.SelectSingleNode("./*[local-name() = 'Project']");
        var attrib  = project?.Attributes["Sdk"];

        return(attrib != null);
    }
Example #33
0
    public void deleteXml()
    {
        string filepath = Application.dataPath + @"/my.xml";
        if(File.Exists (filepath))
        {
             XmlDocument xmlDoc = new XmlDocument();
             xmlDoc.Load(filepath);
             XmlNodeList nodeList=xmlDoc.SelectSingleNode("transforms").ChildNodes;
             foreach(XmlElement xe in nodeList)
             {
                if(xe.GetAttribute("id")=="1")
                {
                    xe.RemoveAttribute("id");
                }

                foreach(XmlElement x1 in xe.ChildNodes)
                {
                    if(x1.Name == "z")
                    {
                        x1.RemoveAll();

                    }
                }
             }
             xmlDoc.Save(filepath);
             Debug.Log("deleteXml OK!");
        }
    }
Example #34
0
        ///// <summary>
        ///// 读取配置信息
        ///// </summary>
        ///// <param name="config"></param>
        //public static DBViewerConfig GetConfig(string fileName)
        //{
        //    XmlDocument doc = new XmlDocument();
        //    doc.Load(fileName);
        //    XmlNode node = doc.SelectSingleNode("//dbtype");
        //    DBViewerConfig config = DBViewerConfig.Create(node);
        //    return config;
        //}

        /// <summary>
        /// 读取默认的配置信息
        /// </summary>
        /// <param name="config"></param>
        public static DBViewerConfig GetConfig(string fileName)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(fileName);
            XmlNode        root   = doc?.SelectSingleNode("/dbTypes");
            var            type   = root.Attributes["default"].Value;
            XmlNode        node   = root?.SelectSingleNode($"//dbtype[@type='{type}']");
            DBViewerConfig config = DBViewerConfig.Create(node);

            return(config);
        }
Example #35
0
        protected virtual string GetXmlAttributeValue(string linkXml, string attributeName)
        {
            XmlDocument xmlDocument = XmlUtil.LoadXml(linkXml);

            XmlNode node = xmlDocument?.SelectSingleNode("/link");

            if (node == null)
            {
                return(string.Empty);
            }

            return(XmlUtil.GetAttribute(attributeName, node));
        }
        /// <summary>
        /// Gets the specified data element from the XmlDataProvider in the resource dictionary.
        /// </summary>
        /// <param name="xpathQuery">An XPath query to the XML element to retrieve.</param>
        /// <returns>The resulting string value for the specified XML element.
        /// Returns empty string if resource element couldn't be found.</returns>
        String GetLogicalResourceString(String xpathQuery)
        {
            String result = String.Empty;
            // get the About xml information from the resources.
            XmlDocument doc = ResourceXmlDocument;
            // if we found the XmlDocument, then look for the specified data.
            XmlNode node = doc?.SelectSingleNode(xpathQuery);

            if (node != null)
            {
                result = node is XmlAttribute ? node.Value : node.InnerText;
            }
            return(result);
        }
Example #37
0
        private static string GetXmlns(string url)
        {
            if (xmlnsList.ContainsKey(url))
            {
                return(xmlnsList[url] as string);
            }

            XmlDocument doc = GetXmlDocument(url);

            string xmlns = doc?.SelectSingleNode("//@targetNamespace")?.Value ?? "";

            xmlnsList.Add(url, xmlns);

            return(xmlns);
        }
Example #38
0
        private static string GetElementFormDefault(string url)
        {
            if (elementFormDefaultList.ContainsKey(url))
            {
                return(elementFormDefaultList[url] as string);
            }

            XmlDocument doc = GetXmlDocument(url);

            string elementFormDefault = doc?.SelectSingleNode("//@elementFormDefault")?.Value ?? "";

            elementFormDefaultList.Add(url, elementFormDefault);

            return(elementFormDefault);
        }
        private string?GetSummary(PropertyInfo memberInfo)
        {
            if (_xmlDoc == null)
            {
                LoadXmlDoc();
            }

            var path = "P:" + memberInfo.DeclaringType?.FullName + "." + memberInfo.Name;
            var node = _xmlDoc?.SelectSingleNode("//member[starts-with(@name, '" + path + "')]");

            if (node == null)
            {
                return(null);
            }

            return(Regex.Replace(node.InnerXml, @"\s+", " "));
        }
        string GetTypeDoc(Type type)
        {
            if (type == null)
            {
                return(null);
            }
            XmlDocument doc = GetAssemblyDoc(type.Assembly);

            XmlNode typedoc = doc?.SelectSingleNode($"doc/members/member[@name='T:{type.FullName}']");

            XmlNode remarksnode = typedoc?.SelectSingleNode("remarks");

            if (remarksnode != null)
            {
                return(ExtractSummary(typedoc.SelectSingleNode("summary")) + "\n" + ExtractSummary(remarksnode));
            }
            return(ExtractSummary(typedoc?.SelectSingleNode("summary")));
        }
        string GetPropertyDoc(System.Reflection.PropertyInfo pi)
        {
            if (pi.DeclaringType == null)
            {
                return(null);
            }

            XmlDocument doc = GetAssemblyDoc(pi.DeclaringType.Assembly);

            XmlNode propertydoc = doc?.SelectSingleNode($"doc/members/member[@name='P:{pi.DeclaringType.FullName}.{pi.Name}']");
            XmlNode remarksnode = propertydoc?.SelectSingleNode("remarks");

            if (remarksnode != null)
            {
                return(ExtractSummary(propertydoc.SelectSingleNode("summary")) + "\n" + ExtractSummary(remarksnode));
            }
            return(ExtractSummary(propertydoc?.SelectSingleNode("summary")));
        }
Example #42
0
        /// <summary>
        /// Helper method to get a cumulative probability table from XML
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="parentNodeName"></param>
        /// <param name="entryNodeName"></param>
        /// <returns></returns>
        public static Dictionary <string, double> GetProbTable(XmlDocument xml, string parentNodeName,
                                                               string entryNodeName)
        {
            const string WEIGHT  = "prob";
            var          dictOut = new Dictionary <string, double>();
            var          elems   = xml?.SelectSingleNode($"//{parentNodeName}");

            if (elems == null || !elems.HasChildNodes)
            {
                return(dictOut);
            }

            foreach (var node in elems.ChildNodes)
            {
                var elem = node as XmlElement;
                if (elem == null)
                {
                    continue;
                }
                var key    = elem.Attributes[entryNodeName]?.Value;
                var strVal = elem.Attributes[WEIGHT]?.Value;

                if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(strVal))
                {
                    continue;
                }

                if (!double.TryParse(strVal, out var val))
                {
                    continue;
                }

                if (dictOut.ContainsKey(key))
                {
                    dictOut[key] = val;
                }
                else
                {
                    dictOut.Add(key, val);
                }
            }
            return(dictOut);
        }
Example #43
0
        protected virtual void ParseLinkAttributes(string link)
        {
            Assert.ArgumentNotNull(link, "link");
            XmlDocument xmlDocument = XmlUtil.LoadXml(link);

            XmlNode node = xmlDocument?.SelectSingleNode("/link");

            if (node == null)
            {
                return;
            }

            this.AnalyticsLinkAttributes[LinkTrackerConstants.GoalAttributeName]       = XmlUtil.GetAttribute(LinkTrackerConstants.GoalAttributeName, node);
            this.AnalyticsLinkAttributes[LinkTrackerConstants.GoalTriggerAttName]      = XmlUtil.GetAttribute(LinkTrackerConstants.GoalTriggerAttName, node);
            this.AnalyticsLinkAttributes[LinkTrackerConstants.GoalDataAttName]         = XmlUtil.GetAttribute(LinkTrackerConstants.GoalDataAttName, node);
            this.AnalyticsLinkAttributes[LinkTrackerConstants.PageEventAttributeName]  = XmlUtil.GetAttribute(LinkTrackerConstants.PageEventAttributeName, node);
            this.AnalyticsLinkAttributes[LinkTrackerConstants.PageEventTriggerAttName] = XmlUtil.GetAttribute(LinkTrackerConstants.PageEventTriggerAttName, node);
            this.AnalyticsLinkAttributes[LinkTrackerConstants.PageEventDataAttName]    = XmlUtil.GetAttribute(LinkTrackerConstants.PageEventDataAttName, node);
        }
Example #44
0
        protected virtual string GetXmlAttributeValue(string linkXml, string attributeName)
        {
            try
            {
                XmlDocument xmlDocument = XmlUtil.LoadXml(linkXml);

                XmlNode node = xmlDocument?.SelectSingleNode("/link");
                if (node == null)
                {
                    return(string.Empty);
                }
                return(XmlUtil.GetAttribute(attributeName, node));
            }
            // Ignore various parsing exceptions as other fields can be false positives starting with "<a"
            catch (XmlException ex)
            {
                Sitecore.Diagnostics.Log.Debug($"LinkTracker - Unable to parse XML: {ex.Message}", this);
                return(string.Empty);
            }
        }
Example #45
0
        public UsStateData(string name)
        {
            const string REGION = "region";
            const string STATE  = "state";

            _nodeName = STATE;
            if (string.IsNullOrWhiteSpace(name) || string.Equals(name, "United States", StringComparison.OrdinalIgnoreCase))
            {
                _nodeName  = "national";
                _stateName = "United States";
            }
            else
            {
                var usState = UsState.GetState(name);
                if (usState == null)
                {
                    return;
                }
                _stateName = usState.ToString();
            }

            UsStateDataXml = UsStateDataXml ??
                             Core.XmlDocXrefIdentifier.GetEmbeddedXmlDoc(US_STATES_DATA,
                                                                         Assembly.GetExecutingAssembly());
            var myNameNode = UsStateDataXml?.SelectSingleNode($"//{_nodeName}[@{NAME}='{_stateName}']") as XmlElement;

            if (myNameNode == null)
            {
                return;
            }
            if (myNameNode.HasAttribute(REGION) &&
                Enum.TryParse(myNameNode.Attributes[REGION].Value, out AmericanRegion reg))
            {
                Region = reg;
            }
            AverageEarnings = GetAvgEarningsPerYear(myNameNode);
            GetEmploymentSectorData(UsStateDataXml);
            GetEduData(UsStateDataXml);
            GetViolentCrimeData(UsStateDataXml);
            GetPropertyCrimeData(UsStateDataXml);
        }
Example #46
0
        public static string GetString(XmlDocument xd, string path)
        {
            var node = xd?.SelectSingleNode(path);

            if (node == null)
            {
                return("");
            }
            if (node.Attributes != null && "TEXT" != node.Attributes["Type"].Value)
            {
                return("");
            }
            try
            {
                return(node.InnerText);
            }
            catch
            {
                return("");
            }
        }
Example #47
0
        public static double GetDouble(XmlDocument xd, string path)
        {
            var node = xd?.SelectSingleNode(path);

            if (node == null)
            {
                return(0);
            }
            if (node.Attributes != null && "SINGLE" != node.Attributes["Type"].Value)
            {
                return(0);
            }
            try
            {
                return(double.Parse(node.InnerText));
            }
            catch
            {
                return(0);
            }
        }
Example #48
0
        public static DateTime?GetTime(XmlDocument xd, string path)
        {
            var node = xd?.SelectSingleNode(path);

            if (node == null)
            {
                return(null);
            }
            if (node.Attributes != null && "DATE" != node.Attributes["Type"].Value)
            {
                return(null);
            }
            try
            {
                return(DateTime.Parse(node.InnerText));
            }
            catch
            {
                return(null);
            }
        }
Example #49
0
        string extractTextFromHTML(string html, ref string?color)
        {
            // the text to return
            string res = "";

            // text is stored in html inside the .mcf
            // html basically is xml so... parse it as xml
            XmlDocument doc = new XmlDocument();

            doc?.LoadXml(html);

            // get the node that contains span objects for each line of text
            XmlNode node = doc?.SelectSingleNode("html/body/table/tr/td");

            if (node == null)
            {
                Log.Error("Text node not found. Stopping text parsing.");
                return("");
            }

            // extract text from each <span> and store in single string with newline character
            string styleInfo = "";

            foreach (XmlNode p in node.ChildNodes)
            {
                XmlNode span = p.SelectSingleNode("span");
                res      += span?.InnerText + "\n"; // if span exists... add text + newline
                styleInfo = getAttributeStr(span, "style");
            }

            if (color != null && styleInfo.Contains("color:"))
            {
                string[] t        = styleInfo.Split("color:");
                string   colorhex = t.Last().Split(";").First();
                color = colorhex.Insert(1, "ff");
            }

            // return all lines
            return(res);
        }
Example #50
0
        internal void AddRemoteConfig(XmlDocument remoteConfig)
        {
            if (remoteConfig != null && remoteConfig.InnerText != "")
            {
                // add RemoteConfiguration without the products list
                XmlDocument remoteConfigHeader = (XmlDocument)remoteConfig.CloneNode(true);
                remoteConfigHeader?.SelectSingleNode("//RemoteConfiguration")?.RemoveChild(remoteConfigHeader?.SelectSingleNode("//RemoteConfiguration/Products"));

                XmlParser.SetNode(xmlDoc, remoteConfigHeader.DocumentElement);
                XmlNodeList remoteProducts = remoteConfig.SelectNodes("//RemoteConfiguration/Products/Product");

                // add the products lists to Products
                if (remoteProducts.Count > 0)
                {
                    for (int i = (remoteProducts.Count - 1); i >= 0; i--)
                    {
                        XmlNode remoteProduct = remoteProducts[i];
                        XmlParser.SetNode(xmlDoc, xmlDoc.SelectSingleNode("//Products"), remoteProduct, false);
                    }
                }
            }
        }
        XmlNode GetIndexerDocFromType(Type type, System.Reflection.PropertyInfo method)
        {
            XmlDocument doc        = GetAssemblyDoc(type.Assembly);
            string      membername = $"{type.FullName}.{method.Name}({string.Join(",", method.GetIndexParameters().Select(p => p.ParameterType.FullName))})";

            XmlNode doctag = doc?.SelectSingleNode($"doc/members/member[@name='P:{membername}']");

            if (doctag == null)
            {
                return(null);
            }

            if (doctag.ChildNodes.Cast <XmlNode>().Any(c => c.Name == "inheritdoc"))
            {
                foreach (Type interfacetype in type.GetInterfaces())
                {
                    XmlNode summarydoc = GetIndexerDocFromType(interfacetype, method);
                    if (summarydoc != null)
                    {
                        return(summarydoc);
                    }
                }

                if (type.BaseType != null && type != typeof(object))
                {
                    XmlNode summarydoc = GetIndexerDocFromType(type.BaseType, method);
                    if (summarydoc != null)
                    {
                        return(summarydoc);
                    }
                }
                return(null);
            }

            return(doctag);
        }
Example #52
0
        public VPack(string name, string source, IEnumerable <string> aliases = null, XmlDocument srcxml = null)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Initializing " + name);
            Console.ResetColor();

            Name    = name;
            Source  = source;
            TempDir = VpmConfig.Instance.VpmTempDir + "\\" + name;
            if (aliases != null)
            {
                Aliases.AddRange(aliases);
            }

            var authornode = srcxml?.SelectSingleNode("/vpack/meta/author");

            if (authornode != null)
            {
                Author = authornode.InnerText.Trim();
            }

            Directory.CreateDirectory(TempDir);

            var xmldoc = srcxml;

            if (source.StartsWith("vpm://", true, CultureInfo.InvariantCulture) ||
                source.StartsWith("vpms://", true, CultureInfo.InvariantCulture))
            {
                xmldoc = VpmUtils.ParseAndValidateXmlFile(source);
            }

            if (CloneFromGit(true))
            {
                var vpackfiles = Directory.GetFiles(TempDir, "*.vpack");
                if ((vpackfiles.Length > 0) && (xmldoc == null))
                {
                    xmldoc = VpmUtils.ParseAndValidateXmlFile(vpackfiles[0]);
                }
            }
            if (xmldoc != null)
            {
                RawXml = xmldoc.ToString();
                var licensenode = xmldoc.SelectSingleNode("/vpack/meta/license");
                LicenseUrl = licensenode?.InnerText.Trim() ?? "http://www.imxprs.com/free/microdee/vpmnolicense";

                var namenode = xmldoc.SelectSingleNode("/vpack/meta/name");
                if (namenode == null)
                {
                    Console.WriteLine(
                        "WARNING: VPack XML doesn't contain name. Using " + Name + " from other sources.");
                }
                else
                {
                    if (!string.Equals(Name.Trim(), namenode.InnerText.Trim(), StringComparison.CurrentCultureIgnoreCase))
                    {
                        Console.WriteLine(
                            "WARNING: VPack XML says pack is called " + namenode.InnerText.Trim() +
                            ", but using " + Name + " to avoid conflicts");
                    }
                }
                var installnode = xmldoc.SelectSingleNode("/vpack/install");
                if (installnode == null)
                {
                    throw new Exception("VPack doesn't contain installing script.");
                }
                InstallScript = installnode.InnerText;

                var nugetnode = xmldoc.SelectSingleNode("/vpack/nuget");
                if (nugetnode != null)
                {
                    NugetPackages = nugetnode.ChildNodes;
                }

                var dependenciesnode = xmldoc.SelectSingleNode("/vpack/meta/dependencies");
                if (dependenciesnode != null)
                {
                    var nodelist = dependenciesnode.ChildNodes;
                    for (int i = 0; i < nodelist.Count; i++)
                    {
                        var dependencynode = nodelist.Item(i);
                        if (dependencynode == null)
                        {
                            continue;
                        }
                        if (dependencynode.Name != "dependency")
                        {
                            Console.ForegroundColor = ConsoleColor.Gray;
                            Console.WriteLine("Unknown node in Dependencies: " + dependencynode.Name + ". Moving on.");
                            Console.ResetColor();
                            continue;
                        }
                        var dnamenode    = dependencynode["name"];
                        var dsrcnode     = dependencynode["source"];
                        var daliasesnode = dependencynode["aliases"];

                        if ((dnamenode == null) || (dsrcnode == null))
                        {
                            throw new Exception("Insufficient data to parse dependency.");
                        }

                        var dname = dnamenode.InnerText.Trim();
                        if (VpmUtils.IsPackAlreadyInTemp(dname))
                        {
                            Console.WriteLine(dname + " is already in vpm temp folder. Ignoring");
                            continue;
                        }
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("Parsing " + dname);
                        Console.ResetColor();
                        var dsrc = dsrcnode.InnerText.Trim();

                        List <string> aliaslist = null;
                        if (daliasesnode != null)
                        {
                            var dantext = daliasesnode.InnerText;
                            aliaslist = dantext.Split(',').ToList();
                            for (int j = 0; j < aliaslist.Count; j++)
                            {
                                aliaslist[j] = aliaslist[j].Trim();
                            }
                        }
                        string matchedname;
                        if (VpmUtils.IsPackExisting(dname, aliaslist, out matchedname))
                        {
                            Console.WriteLine(dname + " seems to be there already.");
                            var replaceit = !Args.GetAmbientArgs <VpmArgs>().Quiet;
                            if (replaceit)
                            {
                                replaceit = VpmUtils.PromptYayOrNay(
                                    "Do you want to replace it?",
                                    "WARNING: Original pack will be deleted!\nWARNING: If anything goes wrong during installation original pack won't be recovered.");
                            }
                            if (!replaceit)
                            {
                                continue;
                            }
                            var aliasdir = Path.Combine(Args.GetAmbientArgs <VpmArgs>().VVVVDir, "packs", matchedname);
                            VpmUtils.DeleteDirectory(aliasdir, true);
                        }
                        var newvpack = new VPack(dname, dsrc, aliaslist);
                        Dependencies.Add(newvpack);
                    }
                }
            }
            else
            {
                ScriptSource();
            }
            VpmConfig.Instance.PackList.Add(this);
        }
Example #53
0
 public static XmlNode GetXmlNode(XmlDocument xd, string path)
 {
     return(xd?.SelectSingleNode(path));
 }
Example #54
0
        public string Macro(string innerText, XmlDocument xmlDoc)
        {
            if (string.IsNullOrEmpty(innerText))
            {
                return(string.Empty);
            }
            string endString = innerText.ToLower().Substring(1).TrimEnd(',', '.');
            string macroName, macroPool;

            if (endString.Contains('_'))
            {
                string[] split = endString.Split('_');
                macroName = split[0];
                macroPool = split[1];
            }
            else
            {
                macroName = macroPool = endString;
            }

            //$DOLLAR is defined elsewhere to prevent recursive calling
            if (macroName == "street")
            {
                if (!string.IsNullOrEmpty(_objCharacter.Alias))
                {
                    return(_objCharacter.Alias);
                }
                return("Alias ");
            }
            if (macroName == "real")
            {
                if (!string.IsNullOrEmpty(_objCharacter.Name))
                {
                    return(_objCharacter.Name);
                }
                return("Unnamed John Doe ");
            }
            if (macroName == "year")
            {
                if (int.TryParse(_objCharacter.Age, out int year))
                {
                    if (int.TryParse(macroPool, out int age))
                    {
                        return((DateTime.UtcNow.Year + 62 + age - year).ToString());
                    }
                    return((DateTime.UtcNow.Year + 62 - year).ToString());
                }
                return(string.Format("(ERROR PARSING \"{0}\")", _objCharacter.Age));
            }

            //Did not meet predefined macros, check user defined

            string searchString = "/chummer/storybuilder/macros/" + macroName;

            XmlNode userMacro = xmlDoc?.SelectSingleNode(searchString);

            if (userMacro != null)
            {
                if (userMacro.FirstChild != null)
                {
                    //Already defined, no need to do anything fancy
                    if (!persistenceDictionary.TryGetValue(macroPool, out string selected))
                    {
                        if (userMacro.FirstChild.Name == "random")
                        {
                            //Any node not named
                            XmlNodeList possible = userMacro.FirstChild.SelectNodes("./*[not(self::default)]");
                            if (possible != null && possible.Count > 0)
                            {
                                if (possible.Count > 1)
                                {
                                    do
                                    {
                                        _intModuloTemp = _objRandom.Next();
                                    }while (_intModuloTemp >= int.MaxValue - int.MaxValue % possible.Count); // Modulo bias removal
                                }
                                else
                                {
                                    _intModuloTemp = 1;
                                }
                                selected = possible[_intModuloTemp % possible.Count].Name;
                            }
                        }
                        else if (userMacro.FirstChild.Name == "persistent")
                        {
                            //Any node not named
                            XmlNodeList possible = userMacro.FirstChild.SelectNodes("./*[not(self::default)]");
                            if (possible != null && possible.Count > 0)
                            {
                                if (possible.Count > 1)
                                {
                                    do
                                    {
                                        _intModuloTemp = _objRandom.Next();
                                    }while (_intModuloTemp >= int.MaxValue - int.MaxValue % possible.Count); // Modulo bias removal
                                }
                                else
                                {
                                    _intModuloTemp = 1;
                                }
                                selected = possible[_intModuloTemp % possible.Count].Name;
                                persistenceDictionary.Add(macroPool, selected);
                            }
                        }
                        else
                        {
                            return(string.Format("(Formating error in  $DOLLAR{0} )", macroName));
                        }
                    }

                    if (!string.IsNullOrEmpty(selected) && userMacro.FirstChild[selected] != null)
                    {
                        return(userMacro.FirstChild[selected].InnerText);
                    }
                    else if (userMacro.FirstChild["default"] != null)
                    {
                        return(userMacro.FirstChild["default"].InnerText);
                    }
                    else
                    {
                        return(string.Format("(Unknown key {0} in  $DOLLAR{1} )", macroPool, macroName));
                    }
                }
                else
                {
                    return(userMacro.InnerText);
                }
            }
            return(string.Format("(Unknown Macro  $DOLLAR{0} )", innerText.Substring(1)));
        }
Example #55
0
        private static bool generateXSDNode(XmlDocument output, string[] files, string assetNodeName, string assetRefTypeName, string srcAttName)
        {
            bool success = true;;
            Dictionary <string, object> assetNameSet = new Dictionary <string, object>();

            string xpath = "xs:schema/xs:simpleType[@name='" + assetRefTypeName + "']/xs:union/xs:simpleType/xs:restriction";
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(output.NameTable);

            nsmgr.AddNamespace("xs", XMLNS);
            XmlNode outRestrictionNode = output.SelectSingleNode(xpath, nsmgr);

            if (outRestrictionNode == null)
            {
                Console.WriteLine("读取原始XSD文件时出错, 找不到结点:" + xpath);
                return(false);
            }

            outRestrictionNode.RemoveAll();
            XmlAttribute outRestrictionBaseAtt = output.CreateAttribute("base");

            outRestrictionBaseAtt.Value = "AssetRef";
            outRestrictionNode.Attributes.Append(outRestrictionBaseAtt);


            int assetCounter = 0;

            foreach (string inputPath in files)
            {
                XmlDocument input = new XmlDocument();
                try
                {
                    input.Load(inputPath);
                }
                catch (IOException e)
                {
                    Console.WriteLine("读取文件{0}时出错,已跳过该文件({1})", inputPath, e.Message);
                    return(false);
                }
                catch (XmlException e)
                {
                    Console.WriteLine("解析文件{0}时出错,文件中可能存在语法错误,已跳过该文件({1})", inputPath, e.Message);
                    return(false);
                }


                XmlNodeList inAssetList = input.GetElementsByTagName(assetNodeName);

                foreach (XmlNode inAssetNode in inAssetList)
                {
                    string assetName = inAssetNode.Attributes["Name"].Value;
                    if (assetNameSet.ContainsKey(assetName))
                    {
                        Console.WriteLine("资源名\"{0}\"被重复定义。", assetName);
                        success = false;
                        continue;
                    }

                    assetNameSet.Add(assetName, null);

                    XmlElement   outEnumElem     = output.CreateElement("xs:enumeration", XMLNS);
                    XmlAttribute outEnumAttValue = output.CreateAttribute("value");
                    outEnumAttValue.Value = assetName;
                    outEnumElem.Attributes.Append(outEnumAttValue);

                    if (srcAttName != null)
                    {
                        XmlElement annotationElem = output.CreateElement("xs:annotation", XMLNS);
                        XmlElement docElem        = output.CreateElement("xs:documentation", XMLNS);
                        docElem.InnerText = inAssetNode.Attributes["src"].Value;
                        annotationElem.AppendChild(docElem);
                        outEnumElem.AppendChild(annotationElem);
                    }

                    outRestrictionNode.AppendChild(outEnumElem);

                    assetCounter++;
                }
            }

            if (success)
            {
                Console.WriteLine("为{0}生成了{1}个预定义资源的XSD", assetNodeName, assetCounter);
            }

            return(success);
        }
Example #56
0
    protected void initTranslationTable()
    {
        // if none was chosen, on site.master.cs the first one will be selected as default
        ProjectHelper.ProjectInfo Project = (ProjectHelper.ProjectInfo)Session["CurrentlyChosenProject"];
        string ProjDirectory = ConfigurationManager.AppSettings["ProjectDirectory"].ToString() + Project.Folder + "\\";
        string Language      = User.Identity.getUserLanguage(Session);
        string SourceLang    = User.Identity.GetSourceLanguage();

        SelectedProject.Text = Project.Name + " files";

        // Getting Directory + Language + ".xml" - if it doesn't exist, it will automatically be created on percentage calculation
        if (!File.Exists(ProjDirectory + Language + ".xml"))
        {
            XMLFile.ComputePercentage(Project, Language, null, SourceLang);
        }


        if (!File.Exists(ProjDirectory + Language + ".xml"))
        {
            showError("Language file for '" + Language + "' could not be created!"); return;
        }
        else
        {
            XmlDocument LanguageXML = XMLFile.GetXMLDocument(ProjDirectory + Language + ".xml");

            XmlNodeList AllFiles = LanguageXML.SelectNodes("/files[@language=\"" + Language + "\"]/file");

            DataSet oDs = new DataSet();
            oDs.ReadXml(ProjDirectory + Language + ".xml");

            if (oDs.Tables.Count >= 2)
            {
                FileList.DataSource = oDs.Tables[1];
            }

            FileList.DataBind();
        }


        //Check if a file is selected
        if (Session["SelectedFilename"] != null)
        {
            CurrentFile.Text = "Selected file: " + Convert.ToString(Session["SelectedFilename"]);
            Save.Visible     = true;

            XmlDocument SourceFile;

            if (Directory.Exists(Path.Combine(ProjDirectory, SourceLang)))
            {
                SourceFile = XMLFile.GetXMLDocument(Path.Combine(ProjDirectory, SourceLang, Convert.ToString(Session["SelectedFilename"]) + "." + SourceLang + ".resx"));
            }
            else
            {
                SourceFile = XMLFile.GetXMLDocument(ProjDirectory + Convert.ToString(Session["SelectedFilename"]) + ".resx");
            }

            if (SourceFile == null)
            {
                Session["SelectedFilename"] = null;
                Response.Redirect("/Account/Default.aspx"); // redirect to homepage, as this selected file does not longer seem to exist
                return;
            }

            XmlDocument TranslatedFile = XMLFile.GetXMLDocument(ProjDirectory + Language + "\\" + Convert.ToString(Session["SelectedFilename"]) + "." + Language + ".resx");
            DataTable   Table          = new DataTable();
            Table.Columns.Add("TextName");
            Table.Columns.Add("English");
            Table.Columns.Add("Translation");
            Table.Columns.Add("Comment");


            foreach (XmlNode Text in SourceFile.SelectNodes("/root/data"))
            {
                DataRow Row = Table.NewRow();
                Row["TextName"] = Text.Attributes["name"].InnerText;
                Row["English"]  = Server.HtmlEncode(Text.SelectSingleNode("value")?.InnerText);
                Row["Comment"]  = TranslatedFile?.SelectSingleNode("/root/data[@name=\"" + Row["Textname"].ToString() + "\"]/comment")?.InnerText ?? "";

                XmlNode Translated = TranslatedFile?.SelectSingleNode("/root/data[@name=\"" + Row["Textname"].ToString() + "\"]/value");
                if (Translated == null)
                {
                    Row["Translation"] = string.Empty;
                }
                else
                {
                    Row["Translation"] = Server.HtmlEncode(Translated.InnerText);
                }

                bool CanBeAdded = true;

                foreach (String notToCheck in XMLFile.NotArgs)
                {
                    if (Row["TextName"].ToString().Contains("." + notToCheck) ||
                        String.IsNullOrEmpty(Row["English"].ToString()))
                    {
                        CanBeAdded = false;
                    }
                }

                if (CanBeAdded && (!cb_showOnlyUntr.Checked || String.IsNullOrEmpty(Row["Translation"].ToString())))
                {
                    Table.Rows.Add(Row);
                }
            }
            TextElements.DataSource = Table;
            TextElements.DataBind();
            Save.Visible = true;
        }
        else
        {
            Save.Visible = false;
        }
    }
Example #57
0
 /// <summary>
 /// Gets value of give node
 /// </summary>
 /// <param name="xmlDoc">Document to be checked</param>
 /// <param name="nodeName">Name of the node which values should be returned</param>
 /// <returns>Value of the node. If node is nothing returns empty string</returns>
 public static string GetXMLNodeValue(XmlDocument xmlDoc, string nodeName) => xmlDoc?.SelectSingleNode(nodeName)?.InnerText ?? "";
Example #58
0
        /// <summary>
        /// This combines the conceptual and API intermediate TOC files into
        /// one file ready for transformation to the help format-specific
        /// TOC file formats.
        /// </summary>
        private void CombineIntermediateTocFiles()
        {
            XmlAttribute attr;
            XmlDocument  conceptualXml = null, tocXml;
            XmlElement   docElement;
            XmlNodeList  allNodes;
            XmlNode      node, parent;
            bool         wasModified = false;
            int          insertionPoint;

            this.ReportProgress(BuildStep.CombiningIntermediateTocFiles,
                                "Combining conceptual and API intermediate TOC files...");

            if (this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
            {
                return;
            }

            this.ExecutePlugIns(ExecutionBehaviors.Before);

            // Load the TOC files
            if (toc != null && toc.Count != 0)
            {
                conceptualXml = new XmlDocument();
                conceptualXml.Load(workingFolder + "_ConceptualTOC_.xml");
            }

            tocXml = new XmlDocument();
            tocXml.Load(workingFolder + "toc.xml");

            // Add a root namespace container for the Prototype style?  The Hana
            // and VS2005 styles add one automatically if requested.
            if (project.RootNamespaceContainer && presentationParam == "prototype" &&
                !String.IsNullOrEmpty(namespacesTopic))
            {
                node = tocXml.CreateElement("topic");

                attr       = tocXml.CreateAttribute("id");
                attr.Value = "R:Project";
                node.Attributes.Append(attr);

                attr       = tocXml.CreateAttribute("file");
                attr.Value = namespacesTopic;
                node.Attributes.Append(attr);

                allNodes = tocXml.SelectNodes("topics/topic");

                foreach (XmlNode n in allNodes)
                {
                    n.ParentNode.RemoveChild(n);

                    node.AppendChild(n);
                }

                tocXml.DocumentElement.AppendChild(node);
                wasModified = true;
            }

            // Merge the conceptual and API TOCs into one?
            if (conceptualXml != null)
            {
                // Remove the root content container if present as we don't need
                // it for the other formats.
                if ((project.HelpFileFormat & HelpFileFormat.MSHelpViewer) != 0 &&
                    !String.IsNullOrEmpty(this.RootContentContainerId))
                {
                    docElement = conceptualXml.DocumentElement;
                    node       = docElement.FirstChild;
                    allNodes   = node.SelectNodes("topic");

                    foreach (XmlNode n in allNodes)
                    {
                        n.ParentNode.RemoveChild(n);
                        docElement.AppendChild(n);
                    }

                    node.ParentNode.RemoveChild(node);
                }

                if (String.IsNullOrEmpty(this.ApiTocParentId))
                {
                    // If not parented, the API content is placed above or below the conceptual
                    // content based on the project's ContentPlacement setting.
                    if (project.ContentPlacement == ContentPlacement.AboveNamespaces)
                    {
                        docElement = conceptualXml.DocumentElement;

                        foreach (XmlNode n in tocXml.SelectNodes("topics/topic"))
                        {
                            node = conceptualXml.ImportNode(n, true);
                            docElement.AppendChild(node);
                        }

                        tocXml = conceptualXml;
                    }
                    else
                    {
                        docElement = tocXml.DocumentElement;

                        foreach (XmlNode n in conceptualXml.SelectNodes("topics/topic"))
                        {
                            node = tocXml.ImportNode(n, true);
                            docElement.AppendChild(node);
                        }
                    }
                }
                else
                {
                    // Parent the API content to a conceptual topic
                    parent = conceptualXml.SelectSingleNode("//topic[@id='" + this.ApiTocParentId + "']");

                    // If not found, parent it to the root
                    if (parent == null)
                    {
                        parent = conceptualXml.DocumentElement;
                    }

                    insertionPoint = this.ApiTocOrder;

                    if (insertionPoint == -1 || insertionPoint >= parent.ChildNodes.Count)
                    {
                        insertionPoint = parent.ChildNodes.Count;
                    }

                    foreach (XmlNode n in tocXml.SelectNodes("topics/topic"))
                    {
                        node = conceptualXml.ImportNode(n, true);

                        if (insertionPoint >= parent.ChildNodes.Count)
                        {
                            parent.AppendChild(node);
                        }
                        else
                        {
                            parent.InsertBefore(node, parent.ChildNodes[insertionPoint]);
                        }

                        insertionPoint++;
                    }

                    tocXml = conceptualXml;
                }

                // Fix up empty container nodes by removing the file attribute and setting
                // the ID attribute to the title attribute value.
                foreach (XmlNode n in tocXml.SelectNodes("//topic[@title]"))
                {
                    attr = n.Attributes["file"];

                    if (attr != null)
                    {
                        n.Attributes.Remove(attr);
                    }

                    attr = n.Attributes["id"];

                    if (attr != null)
                    {
                        attr.Value = n.Attributes["title"].Value;
                    }
                }

                wasModified = true;
            }

            // Determine the default topic for Help 1 and website output if one
            // was not specified in a content layout file.
            if (defaultTopic == null)
            {
                node = tocXml.SelectSingleNode("topics/topic");

                if (node != null)
                {
                    defaultTopic = @"html\" + node.Attributes["file"].Value + ".htm";
                }
                else
                {
                    throw new BuilderException("BE0026", "Unable to determine default topic in " +
                                               "toc.xml.  You may need to mark one as the default topic manually.");
                }
            }

            if (wasModified)
            {
                tocXml.Save(workingFolder + "toc.xml");
            }

            this.ExecutePlugIns(ExecutionBehaviors.After);
        }
Example #59
-1
    protected void GameADEd(object sender, EventArgs e)
    {
        XmlDocument xml = new XmlDocument();
        try
        {
            string xmlPath = Server.MapPath( "/Upload/xml/GameAD.xml" );
            if (!File.Exists(xmlPath))
            {
                return;
            }
            xml.Load(xmlPath);

            XmlNode node = xml.SelectSingleNode("//item[@id='" + AdId + "']");

            //node.RemoveChild(node.ChildNodes[1]);//先将整个子节点删除
            //XmlElement xmelem = xml.CreateElement("Content");
            //XmlCDataSection cdata = xml.CreateCDataSection(content.Value);
            //xmelem.AppendChild(cdata);
            //node.AppendChild(xmelem);
            node["Content"].InnerText = "";
            XmlCDataSection cdata = xml.CreateCDataSection(content.Value);
            node.ChildNodes[1].AppendChild(cdata);

            xml.Save(xmlPath);
            CommonManager.Web.RegJs(this, "alert('修改成功!');location.href='gameadsetting.aspx';", false);
        }
        catch(Exception ex) {

            CommonManager.Web.RegJs(this, "alert(\"修改失败!"+ex.Message.Substring(0,39)+"\");location.href=location.href;", false);
        }
    }