Search Results

Search found 83 results on 4 pages for 'selectnodes'.

Page 2/4 | < Previous Page | 1 2 3 4  | Next Page >

  • Refactoring two methods down to one

    - by bflemi3
    I have two methods that almost do the same thing. They get a List<XmlNode> based on state OR state and schoolType and then return a distinct, ordered IEnumerable<KeyValuePair<string,string>>. I know they can be refactored but I'm struggling to determine what type the parameter should be for the linq statement in the return of the method (the last line of each method). I thank you for your help in advance. private IEnumerable<KeyValuePair<string, string>> getAreaDropDownDataSource() { StateInfoXmlDocument stateInfoXmlDocument = new StateInfoXmlDocument(); string schoolTypeXmlPath = string.Format(STATE_AND_SCHOOL_TYPE_XML_PATH, StateOfInterest, ConnectionsLearningSchoolType); var schoolNodes = new List<XmlNode>(stateInfoXmlDocument.SelectNodes(schoolTypeXmlPath).Cast<XmlNode>()); return schoolNodes.Select(x => new KeyValuePair<string, string>(x.Attributes["idLocation"].Value, x.Value)).OrderBy(x => x.Key).Distinct(); } private IEnumerable<KeyValuePair<string, string>> getStateOfInterestDropDownDataSource() { StateInfoXmlDocument stateInfoXmlDocument = new StateInfoXmlDocument(); string schoolTypeXmlPath = string.Format(SCHOOL_TYPE_XML_PATH, ConnectionsLearningSchoolType); var schoolNodes = new List<XmlNode>(stateInfoXmlDocument.SelectNodes(schoolTypeXmlPath).Cast<XmlNode>()); return schoolNodes.Select(x => new KeyValuePair<string, string>(x.Attributes["stateCode"].Value, x.Attributes["stateName"].Value)).OrderBy(x => x.Key).Distinct(); }

    Read the article

  • Html Agility Pack: DescendantsOrSelf() not returning HTML element

    - by Program.X
    I have some HTML, eg: <%@ Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="ContentManagedTargetPage.aspx.cs" Inherits="xxx.ContentManagedTargetPage" %> <%@ Register TagPrefix="CxCMS" Namespace="xxx.ContentManagement.ASPNET.UI" Assembly="xxx.ContentManagement.ASPNET" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> Content Managed </h2> <p> Put content here. [<CxCMS:ContentManagedPlaceHolder Key="keyThingy" runat="server" />] </p> </asp:Content> And I want to find all the instances of the CxCMS:ContentManagedPlaceHolder element. I'm using HTML Agility Pack, which seems the best fit. However, despite looking at the [meagre] documentation, I can't get my code to work. I would expect the following to work: string searchForElement = "CxCMS:ContentManagedPlaceHolder"; IEnumerable<HtmlNode> contentPlaceHolderHtmlNodes = HtmlDocument.DocumentNode.Descendants(searchForElement); int count = contentPlaceHolderHtmlNodes.Count(); But I get nothing back. If I change to DescendantsOrSelf, I get the document node back, "#document" - which is incorrect: string searchForElement = "CxCMS:ContentManagedPlaceHolder"; IEnumerable<HtmlNode> contentPlaceHolderHtmlNodes = HtmlDocument.DocumentNode.DescendantsOrSelf(searchForElement); int count = contentPlaceHolderHtmlNodes.Count(); I also tried using LINQ: string searchForElement = "CxCMS:ContentManagedPlaceHolder"; IEnumerable<HtmlNode> contentPlaceHolderHtmlNodes = HtmlDocument.DocumentNode.DescendantsOrSelf().Where(q=>q.Name==searchForElement); int count = contentPlaceHolderHtmlNodes.Count(); As neither of these methods work, I moved onto using SelectNodes, instead: string searchForElement = "CxCMS:ContentManagedPlaceHolder"; string xPath="//"+searchForElement // "//CxCMS:ContentManagedPlaceHolder" var nodes= HtmlDocument.DocumentNode.SelectNodes(xPath); This just throws the exception: "Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.". I can't find any way of adding namespace management to the HtmlDocument object. What am I missing, here? The DescendantsOrSelf() method works if using a "standard" HTML tag, such as "p", but not the one I have. Surely it should work? (It needs to!)

    Read the article

  • XmlDocument filter nodes by datetime string

    - by Eatdoku
    Trying to apply filter / attribute comparison in the Xmldocument. Obviously , the following code snippet wouldn't work because the expression can't be converted using number() function. (according to the answer of my other question). I'm wondering if there is a way to do the DateTime string comparison in XmlDoc. XmlNodeList test = x2PathDoc.SelectNodes("//Config /Entity [@TargetDateTime> '2010-12-19T03:25:00-08:00']");

    Read the article

  • How to remove all comment tags from XmlDocument

    - by Filburt
    How would i go about to remove all comment tags from a XmlDocument instance? Is there a better way than retrieving a XmlNodeList and iterate over those? XmlNodeList list = xmlDoc.SelectNodes("//comment()"); foreach(XmlNode node in list) { node.ParentNode.RemoveChild(node); }

    Read the article

  • Count Total Number of XmlNodes in C#

    - by mjmcloug
    Hey, I'm trying to find a way to get the total number of child nodes from an XmlNode recursively. That it is to say I want to count all the children, grand children etc. I think its something like node.SelectNodes(<fill in here>).Count but I don't know what the XPath is. Thanks

    Read the article

  • Html Agility Pack: Setting an HtmlNode's Attribute Value isn't reflected in the HtmlDocument.

    - by Avi
    In Html Agility Pack, when I set an attribute of an HtmlNode, should I see this in the HtmlDocument from which the node was selected? Lets say that htmlDocument is an HtmlDocument. So the simplified code looks like this: HtmlNode documentNode = htmlDocument.DocumentNode; HtmlNodeCollection nodeCollection = documentNode.SelectNodes(someXPath); foreach(var node in nodeCollection) if(SomeCondition(node)) node.SetAttributeValue("class","something"); Now, I see the class attribte of node change, but I don't see this change reflected in the htmlDocument's html.

    Read the article

  • How do I perform this XPath query with Linq?

    - by John Hansen
    In the following code I am using XPath to find all of the matching nodes using XPath, and appending the values to a StringBuilder. StringBuilder sb = new StringBuilder(); foreach (XmlNode node in this.Data.SelectNodes("ID/item[@id=200]/DAT[1]/line[position()>1]/data[1]/text()")) { sb.Append(node.Value); } return sb.ToString(); How do I do the same thing, except using Linq to XML instead? Assume that in the new version, this.Data is an XElement object.

    Read the article

  • Cutting large XML file into smaller pieces in C#

    - by NDraskovic
    I have a problem that I'm working on for quite some time now. I have an XML file with over 50000 records (one record has 3 levels). This file is used by one of my applications to control document sending (the record holds, among other informations, the type of document that has to be sent to a certain person). So in my application I load the XML file into a XmlDocument, and then by using SelectNodes method, I create a XmlNodeList from which I read the data I want. The process is like this - our worker takes the persons ID card (simple eith barcode) and reads it with barcode reader. When the barcode value has been read, my application finds the person with that ID in the XML file, and stores the type of the document into a string variable. Then the worker takes the document and reads its barcode, and if the value of documents barcode and the value in the value in the string variable match, the application makes a record that document of type xxxxxxxx will be sent to the person with ID yyyyyyyyy. This is very simple code, it works perfectly for now, and this is how it looks: On textBox1_TextChanged event (worker read persons ID): foreach(XmlNode node in NodeList){ if(String.Compare(node.Attributes.GetNamedItem("ID").Value.ToString(),textBox1.Text)==0) { ControlString = node.ChildNode[3].FirstChild.Attributes.GetNamedItem("doctype").Value.ToString(); break; } } textBox2.Focus(); And on textBox2_TextChanged event (worker read the documents barcode): if(String.Compare(textBox2.Text,ControlString)==0) { //Create a record and insert it into a SQL database } My question is - how will my application perform with larger XML files (I was told that the XML file might be up to 500,000 records large), will this approach be valid, or will I need to cut the file into smaller files. If I have to cut it, please give me an idea with some code samples, I've tried to do it like this: Reading entire record and storing it into a string: private void WriteXml(XmlNode record) { tempXML = record.InnerXml; temp = "<" + record.Name + " code=\"" + record.Attributes.GetNamedItem("code").Value + "\">" + Environment.NewLine; temp += tempXML + Environment.NewLine; temp += "</" + record.Name + ">"; SmallerXMLDocument += temp + Environment.NewLine; temp = ""; i++; } tempXML, temp and SmallerXMLDocument are all string variables. And then in button_Click method I load the XML file into a XmlNodeList (again by using XmlDocument.SelectNodes method) and I try to create one big string value that would hold all records like this: foreach(XmlNode node in nodes) { if(String.Compare(node.ChildNode[3].FirstChild.Attributes.GetNamedItem("doctype").Value.ToString(),doctype1)==0) { WriteXML(node); } } My idea was to create a string value (in this case called SmallerXmlDocument), and when I pass trough the entire XML file, to simply copy the value of that string into a new file. This works, but only for files that have up to 2000 records (and my has way more than that). So, if I need to cut the file into smaller pieces, what would be the best way to do it (keep in mind that there could be up to half a million records in a XML file)? Thanks

    Read the article

  • Custom Content Pipeline with Automatic Serialization Load Error

    - by Direweasel
    I'm running into this error: Error loading "desert". Cannot find type TiledLib.MapContent, TiledLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null. at Microsoft.Xna.Framework.Content.ContentTypeReaderManager.InstantiateTypeReader(String readerTypeName, ContentReader contentReader, ContentTypeReader& reader) at Microsoft.Xna.Framework.Content.ContentTypeReaderManager.GetTypeReader(String readerTypeName, ContentReader contentReader, List1& newTypeReaders) at Microsoft.Xna.Framework.Content.ContentTypeReaderManager.ReadTypeManifest(Int32 typeCount, ContentReader contentReader) at Microsoft.Xna.Framework.Content.ContentReader.ReadHeader() at Microsoft.Xna.Framework.Content.ContentReader.ReadAsset[T]() at Microsoft.Xna.Framework.Content.ContentManager.ReadAsset[T](String assetName, Action1 recordDisposableObject) at Microsoft.Xna.Framework.Content.ContentManager.Load[T](String assetName) at TiledTest.Game1.LoadContent() in C:\My Documents\Dropbox\Visual Studio Projects\TiledTest\TiledTest\TiledTest\Game1.cs:line 51 at Microsoft.Xna.Framework.Game.Initialize() at TiledTest.Game1.Initialize() in C:\My Documents\Dropbox\Visual Studio Projects\TiledTest\TiledTest\TiledTest\Game1.cs:line 39 at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun) at Microsoft.Xna.Framework.Game.Run() at TiledTest.Program.Main(String[] args) in C:\My Documents\Dropbox\Visual Studio Projects\TiledTest\TiledTest\TiledTest\Program.cs:line 15 When trying to run the game. This is a basic demo to try and utilize a separate project library called TiledLib. I have four projects overall: TiledLib (C# Class Library) TiledTest (Windows Game) TiledTestContent (Content) TMX CP Ext (Content Pipeline Extension Library) TiledLib contains MapContent which is throwing the error, however I believe this may just be a generic error with a deeper root problem. EMX CP Ext contains one file: MapProcessor.cs using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content.Pipeline; using Microsoft.Xna.Framework.Content.Pipeline.Graphics; using Microsoft.Xna.Framework.Content.Pipeline.Processors; using Microsoft.Xna.Framework.Content; using TiledLib; namespace TMX_CP_Ext { // Each tile has a texture, source rect, and sprite effects. [ContentSerializerRuntimeType("TiledTest.Tile, TiledTest")] public class DemoMapTileContent { public ExternalReference<Texture2DContent> Texture; public Rectangle SourceRectangle; public SpriteEffects SpriteEffects; } // For each layer, we store the size of the layer and the tiles. [ContentSerializerRuntimeType("TiledTest.Layer, TiledTest")] public class DemoMapLayerContent { public int Width; public int Height; public DemoMapTileContent[] Tiles; } // For the map itself, we just store the size, tile size, and a list of layers. [ContentSerializerRuntimeType("TiledTest.Map, TiledTest")] public class DemoMapContent { public int TileWidth; public int TileHeight; public List<DemoMapLayerContent> Layers = new List<DemoMapLayerContent>(); } [ContentProcessor(DisplayName = "TMX Processor - TiledLib")] public class MapProcessor : ContentProcessor<MapContent, DemoMapContent> { public override DemoMapContent Process(MapContent input, ContentProcessorContext context) { // build the textures TiledHelpers.BuildTileSetTextures(input, context); // generate source rectangles TiledHelpers.GenerateTileSourceRectangles(input); // now build our output, first by just copying over some data DemoMapContent output = new DemoMapContent { TileWidth = input.TileWidth, TileHeight = input.TileHeight }; // iterate all the layers of the input foreach (LayerContent layer in input.Layers) { // we only care about tile layers in our demo TileLayerContent tlc = layer as TileLayerContent; if (tlc != null) { // create the new layer DemoMapLayerContent outLayer = new DemoMapLayerContent { Width = tlc.Width, Height = tlc.Height, }; // we need to build up our tile list now outLayer.Tiles = new DemoMapTileContent[tlc.Data.Length]; for (int i = 0; i < tlc.Data.Length; i++) { // get the ID of the tile uint tileID = tlc.Data[i]; // use that to get the actual index as well as the SpriteEffects int tileIndex; SpriteEffects spriteEffects; TiledHelpers.DecodeTileID(tileID, out tileIndex, out spriteEffects); // figure out which tile set has this tile index in it and grab // the texture reference and source rectangle. ExternalReference<Texture2DContent> textureContent = null; Rectangle sourceRect = new Rectangle(); // iterate all the tile sets foreach (var tileSet in input.TileSets) { // if our tile index is in this set if (tileIndex - tileSet.FirstId < tileSet.Tiles.Count) { // store the texture content and source rectangle textureContent = tileSet.Texture; sourceRect = tileSet.Tiles[(int)(tileIndex - tileSet.FirstId)].Source; // and break out of the foreach loop break; } } // now insert the tile into our output outLayer.Tiles[i] = new DemoMapTileContent { Texture = textureContent, SourceRectangle = sourceRect, SpriteEffects = spriteEffects }; } // add the layer to our output output.Layers.Add(outLayer); } } // return the output object. because we have ContentSerializerRuntimeType attributes on our // objects, we don't need a ContentTypeWriter and can just use the automatic serialization. return output; } } } TiledLib contains a large amount of files including MapContent.cs using System; using System.Collections.Generic; using System.Globalization; using System.Xml; using Microsoft.Xna.Framework.Content.Pipeline; namespace TiledLib { public enum Orientation : byte { Orthogonal, Isometric, } public class MapContent { public string Filename; public string Directory; public string Version = string.Empty; public Orientation Orientation; public int Width; public int Height; public int TileWidth; public int TileHeight; public PropertyCollection Properties = new PropertyCollection(); public List<TileSetContent> TileSets = new List<TileSetContent>(); public List<LayerContent> Layers = new List<LayerContent>(); public MapContent(XmlDocument document, ContentImporterContext context) { XmlNode mapNode = document["map"]; Version = mapNode.Attributes["version"].Value; Orientation = (Orientation)Enum.Parse(typeof(Orientation), mapNode.Attributes["orientation"].Value, true); Width = int.Parse(mapNode.Attributes["width"].Value, CultureInfo.InvariantCulture); Height = int.Parse(mapNode.Attributes["height"].Value, CultureInfo.InvariantCulture); TileWidth = int.Parse(mapNode.Attributes["tilewidth"].Value, CultureInfo.InvariantCulture); TileHeight = int.Parse(mapNode.Attributes["tileheight"].Value, CultureInfo.InvariantCulture); XmlNode propertiesNode = document.SelectSingleNode("map/properties"); if (propertiesNode != null) { Properties = new PropertyCollection(propertiesNode, context); } foreach (XmlNode tileSet in document.SelectNodes("map/tileset")) { if (tileSet.Attributes["source"] != null) { TileSets.Add(new ExternalTileSetContent(tileSet, context)); } else { TileSets.Add(new TileSetContent(tileSet, context)); } } foreach (XmlNode layerNode in document.SelectNodes("map/layer|map/objectgroup")) { LayerContent layerContent; if (layerNode.Name == "layer") { layerContent = new TileLayerContent(layerNode, context); } else if (layerNode.Name == "objectgroup") { layerContent = new MapObjectLayerContent(layerNode, context); } else { throw new Exception("Unknown layer name: " + layerNode.Name); } // Layer names need to be unique for our lookup system, but Tiled // doesn't require unique names. string layerName = layerContent.Name; int duplicateCount = 2; // if a layer already has the same name... if (Layers.Find(l => l.Name == layerName) != null) { // figure out a layer name that does work do { layerName = string.Format("{0}{1}", layerContent.Name, duplicateCount); duplicateCount++; } while (Layers.Find(l => l.Name == layerName) != null); // log a warning for the user to see context.Logger.LogWarning(string.Empty, new ContentIdentity(), "Renaming layer \"{1}\" to \"{2}\" to make a unique name.", layerContent.Type, layerContent.Name, layerName); // save that name layerContent.Name = layerName; } Layers.Add(layerContent); } } } } I'm lost as to why this is failing. Thoughts? -- EDIT -- After playing with it a bit, I would think it has something to do with referencing the projects. I'm already referencing the TiledLib within my main windows project (TiledTest). However, this doesn't seem to make a difference. I can place the dll generated from the TiledLib project into the debug folder of TiledTest, and this causes it to generate a different error: Error loading "desert". Cannot find ContentTypeReader for Microsoft.Xna.Framework.Content.Pipeline.ExternalReference`1[Microsoft.Xna.Framework.Content.Pipeline.Graphics.Texture2DContent]. at Microsoft.Xna.Framework.Content.ContentTypeReaderManager.GetTypeReader(Type targetType, ContentReader contentReader) at Microsoft.Xna.Framework.Content.ContentTypeReaderManager.GetTypeReader(Type targetType) at Microsoft.Xna.Framework.Content.ReflectiveReaderMemberHelper..ctor(ContentTypeReaderManager manager, FieldInfo fieldInfo, PropertyInfo propertyInfo, Type memberType, Boolean canWrite) at Microsoft.Xna.Framework.Content.ReflectiveReaderMemberHelper.TryCreate(ContentTypeReaderManager manager, Type declaringType, FieldInfo fieldInfo) at Microsoft.Xna.Framework.Content.ReflectiveReader1.Initialize(ContentTypeReaderManager manager) at Microsoft.Xna.Framework.Content.ContentTypeReaderManager.ReadTypeManifest(Int32 typeCount, ContentReader contentReader) at Microsoft.Xna.Framework.Content.ContentReader.ReadHeader() at Microsoft.Xna.Framework.Content.ContentReader.ReadAsset[T]() at Microsoft.Xna.Framework.Content.ContentManager.ReadAsset[T](String assetName, Action1 recordDisposableObject) at Microsoft.Xna.Framework.Content.ContentManager.Load[T](String assetName) at TiledTest.Game1.LoadContent() in C:\My Documents\Dropbox\Visual Studio Projects\TiledTest\TiledTest\TiledTest\Game1.cs:line 51 at Microsoft.Xna.Framework.Game.Initialize() at TiledTest.Game1.Initialize() in C:\My Documents\Dropbox\Visual Studio Projects\TiledTest\TiledTest\TiledTest\Game1.cs:line 39 at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun) at Microsoft.Xna.Framework.Game.Run() at TiledTest.Program.Main(String[] args) in C:\My Documents\Dropbox\Visual Studio Projects\TiledTest\TiledTest\TiledTest\Program.cs:line 15 This is all incredibly frustrating as the demo doesn't appear to have any special linking properties. The TiledLib I am utilizing is from Nick Gravelyn, and can be found here: https://bitbucket.org/nickgravelyn/tiledlib. The demo it comes with works fine, and yet in recreating I always run into this error.

    Read the article

  • Html Agility Pack get all elements by class

    - by Adam
    I am taking a stab at html agility pack and having trouble finding the right way to go about this. For example: var findclasses = _doc.DocumentNode.Descendants("div").Where(d => d.Attributes.Contains("class")); However, obviously you can add classes to a lot more then divs so I tried this.. var allLinksWithDivAndClass = _doc.DocumentNode.SelectNodes("//*[@class=\"float\"]"); But that doesn't handle the cases where you add multiple classes and "float" is just one of them like this.. class="className float anotherclassName" Is there a way to handle all of this? I basically want to select all nodes that have a class = and contains float.

    Read the article

  • Select all links from a Html table using XPath (and HtmlAgilityPack)

    - by Adam Asham
    What I am trying to achieve is to extract all links with a href attribute that starts with http://, https:// or /. These links lie within a table (tbody tr td etc) with a certain class. I thought I could specify just the the a element without the whole path to it but it does not seem to work. I get a NullReferenceException at the line that selects the links: var table = doc.DocumentNode.SelectSingleNode("//table[@class='containerTable']"); if (table != null) { foreach (HtmlNode item in table.SelectNodes("a[starts-with(@href, 'https://')]")) { //not working I don't know about any recommendations or best practices when it comes to XPath. Do I create overhead when I query the document two times?

    Read the article

  • Using HTMLAgility Pack to Extract Links

    - by Soham
    Hi Folks, Consider this simplest piece of code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using HtmlAgilityPack; namespace WebScraper { class Program { static void Main(string[] args) { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml("http://www.google.com"); foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]")) { } } } } This effectively doesnt do anything at all, and is copied/inspired from various other StackOverflow questions like this. When compiling this, there is a runtime error which says "Object reference not set to an instance of an object." highlighting the foreach line. I can't understand, why the environment has become irritable to this humble,innocent and useless piece of code. I would also like to know, does HTMLAgilityPack accept HTML classes as nodes?

    Read the article

  • ListView not importing data

    - by ct2k7
    Hello, I'm trying to import data into a listview and this is the code I'm using: Private Sub form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim doc As New XmlDocument doc.Load("http://user:[email protected]/1/statuses/mentions.rss") Dim nodes As XmlNodeList = doc.SelectNodes("Statuses/Status") For Each node As XmlNode In nodes Dim text As String = node.SelectSingleNode("text").InnerText Dim time As String = node.SelectSingleNode("created_at").InnerText Dim screen_name As String = node.SelectSingleNode("user/screen_name").InnerText ListView1.Items.Add(New ListViewItem(New String() {screen_name, text, time})) Next End Sub Any ideas what's going wrong here? User and password are correct.

    Read the article

  • RSS parsing last build Date. Fastest way to do so please.

    - by Paul
    Dim myRequest As System.Net.WebRequest = System.Net.WebRequest.Create(url) Dim myResponse As System.Net.WebResponse = myRequest.GetResponse() Dim rssStream As System.IO.Stream = myResponse.GetResponseStream() Dim rssDoc As New System.Xml.XmlDocument() Try rssDoc.Load(rssStream) Catch nosupport As NotSupportedException Throw nosupport End Try Dim rssItems As System.Xml.XmlNodeList = rssDoc.SelectNodes("rss/channel") 'For i As Integer = 0 To rssItems.Count - 1 Dim rssDetail As System.Xml.XmlNode rssDetail = rssItems.Item(0).SelectSingleNode("lastBuildDate") Folks this is what I'm using to parse an RSS feed for the last updated time. Is there a quicker way? Speed seems to be a bit slow on it as it pulls down the entire feed before parsing.

    Read the article

  • Error loading contents from a XML file into a dropdownlist

    - by Chaitanya
    private void BindCountry() { XmlDocument doc = new XmlDocument(); doc.Load(Server.MapPath("countries.xml")); foreach (XmlNode node in doc.SelectNodes("//country")) { usrlocationddl.Items.Add(new ListItem(node.InnerText, node.Attributes["codes"].InnerText)); //ddlCountry.Items.Add(new ListItem(node.InnerText, node.Attributes["code"].InnerText)); } } The above code am using for loading countries List from an xml file into a dropdown list. But while doing so am encountering a Null Reference error. Object reference not set to an instance of an object. Where in the code should I be changing, so that I can escape the error.

    Read the article

  • Do we need to disconnect from sharepoint? If Yes How? ( using Web Services : C#)

    - by Pari
    Hi, I am using web services to access sharepoint list,sites and documents. Like: List.asmx,Site.asmx e.t.c. My question is that: Do we need to disconnect from sharepoint when using above services? And if yes then How? Example: GetSiteCollection(String login, String password, String url) { Webs ws = new Webs(); try { ws.Credentials = new NetworkCredential(login, password); } catch (Exception ex) { MessageBox.Show(ex.Message); } ws.Url = url + @"/_vti_bin/webs.asmx"; ws.PreAuthenticate = true; XmlNode websiteNode = ws.GetWebCollection(); XmlNodeList nodes = websiteNode.SelectNodes("*"); // getting list set of sites //Now here after this is there any way to disconnect from server? }

    Read the article

  • Parsing tables, cells with Html agility in C#

    - by Kaeso
    I need to parse Html code. More specifically, parse each cell of every rows in all tables. Each row represent a single object and each cell represent different properties. I want to parse these to be able to write an XML file with every data inside (without the useless HTML code). This is the way I thought it out initially but I ran out of ideas: HTML: <tr> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF"> 1 </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="left"> <a href="/ice/player.htm?id=8471675">Sidney Crosby</a> </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="center"> PIT </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="center"> C </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="right"> 39 </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="right"> 32 </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="right"> 33 </td> <td class="statBox sorted" style="border-width:0px 1px 1px 0px; background-color: #E0E0E0" align="right"> <font color="#000000"> 65 </font> </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="right"> 20 </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="right"> 29 </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="right"> 10 </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="right"> 1 </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="right"> 3 </td> <td class="statBox" style="border-width:0px 0px 1px 0px; background-color: #FFFFFF" align="right"> </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="right"> 0 </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="right"> 154 </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="right"> 20.8 </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="right"> 21:54 </td> <td class="statBox" style="border-width:0px 1px 1px 0px; background-color: #FFFFFF" align="right"> 22.6 </td> <td class="statBox" style="border-width:0px 0px 1px 0px; background-color: #FFFFFF" align="right"> 55.7 </td> </tr> C#: using HtmlAgilityPack; using System.Data; namespace Stats { class StatsParser { private string htmlCode; private static string fileName = "[" + DateTime.Now.ToShortDateString() + " NHL Stats].xml"; public StatsParser(string htmlCode) { this.htmlCode = htmlCode; this.ParseHtml(); } public DataTable ParseHtml() { var result = new DataTable(); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(htmlCode); HtmlNode row = doc.DocumentNode.SelectNodes("//tr"); foreach (var statBox in row.SelectNodes("//td[@class='statBox']")) { System.Windows.MessageBox.Show(statBox.InnerText); } } } }

    Read the article

  • how to copy attribute XML node to specified structure or array

    - by jozi
    how to copy attribute XML node to specified structure or array with one command for example public struct PossibilityJavamed { public string derv; public string dervt; public string num; public string gend; } PossibilityJavamed tmpstructnew = tmpstruct; ArrayList alstout = new ArrayList(); XmlNodeList nodeList; nodeList = docHarf.SelectNodes("//adatesmi"); for (int i = 0; i < nodeList.Count; i++) { tmpstructnew.derv = nodeList[i].Attributes["derv"].Value; tmpstructnew.dervt = nodeList[i].Attributes["dervt"].Value; tmpstructnew.num = nodeList[i].Attributes["num"].Value; tmpstructnew.gend = nodeList[i].Attributes["gend"].Value; alstout.Add(tmpstructnew); } but i will do it in one command

    Read the article

  • Avoiding a NullReferenceException

    - by Nikhil K
    I have used this code for extracting urls from web page.But in the line of 'foreach' it is showing Object reference not set to an instance of an object exception. What is the problem? how can i correct that? WebClient client = new WebClient(); string url = "http://www.google.co.in/search?hl=en&q=java&start=10&sa=N"; string source = client.DownloadString(url); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(source); foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href and @rel='nofollow']")) { Console.WriteLine(link.Attributes["href"].Value); }

    Read the article

  • How would I use HTMLAgilityPack to extract the value I want

    - by Nai
    For the given HTML I want the value of id <div class="name" id="john-5745844"> <div class="name" id="james-6940673"> UPDATE This is what I have at the moment HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.Load(new StringReader(pageResponse)); HtmlNode root = htmlDoc.DocumentNode; List<string> anchorTags = new List<string>(); foreach (HtmlNode div in root.SelectNodes("//div[@class='name' and @id]")) { HtmlAttribute att = div.Attributes["id"]; Console.WriteLine(att.Value); } The error I am getting is at the foreach line stating: Object reference not set to an instance of an object.

    Read the article

  • Removing exception

    - by Nikhil K
    I have used this code for extracting urls from web page.But in the line of 'foreach' it is showing Object reference not set to an instance of an object exception. What is the problem? how can i correct that? WebClient client = new WebClient(); string url = "http://www.google.co.in/search?hl=en&q=java&start=10&sa=N"; string source = client.DownloadString(url); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(source); foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href and @rel='nofollow']")) { Console.WriteLine(link.Attributes["href"].Value); }

    Read the article

  • How can i return List of directories instead of url's?

    - by user1741587
    I have this function : private List<string> getLinks(HtmlAgilityPack.HtmlDocument document) { List<string> mainLinks = new List<string>(); var linkNodes = document.DocumentNode.SelectNodes("//a[@href]"); if (linkNodes != null) { foreach (HtmlNode link in linkNodes) { var href = link.Attributes["href"].Value; if (href.StartsWith("http://") == true || href.StartsWith("https://") == true || href.StartsWith("www") == true) // filter for http { mainLinks.Add(href); } } } return mainLinks; } Its getting one url and return list of url's. Instead i want that the function will get a directory for example c:\ And it will return me a List of all directories in c:\ Not subsirectories just the directories in c:\ in my case it should be a List with a 14 directories. Meaning in each index in the List a directory. How can i do it ? Tried with Directory and DirectoryInfo but i just got messed up.

    Read the article

  • c# xml function to check whether a string is equal to a xml attribute, to add selected combobox item

    - by fuch
    i want to check the combobox.selecteditem.tostring() on combobox select in a given xml with several nodes, where each one has an attribute called "name" private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { try { textBox1.AppendText(nameAttributeCheck(comboBox1.SelectedItem.ToString())); } catch { } } private string nameAttributeCheck(string a) { XmlDocument doc = new XmlDocument(); doc.Load("armor.xml"); XmlElement root = doc.DocumentElement; XmlNodeList items = root.SelectNodes("/items"); String result = null; try { foreach (XmlNode item in items) { if (string.Equals(a, item.Attributes["name"].InnerText.ToString())) { result += item.Attributes["picture"].InnerText.ToString(); } } } catch { } return result; } each time i try it, nothing happens

    Read the article

  • Get length of a Dictionary

    - by StealthRT
    Hey all i am new at this Dictionary class in VB.net. I am wanting to reteive how many items in the Dictionary array there are: But doing this: Dim showNumber As Integer = tmpShows.Length Does not seem to yield 4 as it should? The code for the Dictionary i have is this: Dim all = New Dictionary(Of String, Object)() Dim info = New Dictionary(Of String, Object)() info!Station = .SelectSingleNode(".//span[@class='channel']").ChildNodes(3).ChildNodes(2).InnerText info!Shows = From tag In .SelectNodes(".//a[@class='thickbox']") Select New With {.Show = tag.Attributes("title").Value, .Link = tag.Attributes("href").Value} Dim tmpShows = all.Item(info!Station) Dim showNumber As Integer = tmpShows.Length What am i missing in order to get the 4 length i am looking for?

    Read the article

  • Node.js Adventure - Host Node.js on Windows Azure Worker Role

    - by Shaun
    In my previous post I demonstrated about how to develop and deploy a Node.js application on Windows Azure Web Site (a.k.a. WAWS). WAWS is a new feature in Windows Azure platform. Since it’s low-cost, and it provides IIS and IISNode components so that we can host our Node.js application though Git, FTP and WebMatrix without any configuration and component installation. But sometimes we need to use the Windows Azure Cloud Service (a.k.a. WACS) and host our Node.js on worker role. Below are some benefits of using worker role. - WAWS leverages IIS and IISNode to host Node.js application, which runs in x86 WOW mode. It reduces the performance comparing with x64 in some cases. - WACS worker role does not need IIS, hence there’s no restriction of IIS, such as 8000 concurrent requests limitation. - WACS provides more flexibility and controls to the developers. For example, we can RDP to the virtual machines of our worker role instances. - WACS provides the service configuration features which can be changed when the role is running. - WACS provides more scaling capability than WAWS. In WAWS we can have at most 3 reserved instances per web site while in WACS we can have up to 20 instances in a subscription. - Since when using WACS worker role we starts the node by ourselves in a process, we can control the input, output and error stream. We can also control the version of Node.js.   Run Node.js in Worker Role Node.js can be started by just having its execution file. This means in Windows Azure, we can have a worker role with the “node.exe” and the Node.js source files, then start it in Run method of the worker role entry class. Let’s create a new windows azure project in Visual Studio and add a new worker role. Since we need our worker role execute the “node.exe” with our application code we need to add the “node.exe” into our project. Right click on the worker role project and add an existing item. By default the Node.js will be installed in the “Program Files\nodejs” folder so we can navigate there and add the “node.exe”. Then we need to create the entry code of Node.js. In WAWS the entry file must be named “server.js”, which is because it’s hosted by IIS and IISNode and IISNode only accept “server.js”. But here as we control everything we can choose any files as the entry code. For example, I created a new JavaScript file named “index.js” in project root. Since we created a C# Windows Azure project we cannot create a JavaScript file from the context menu “Add new item”. We have to create a text file, and then rename it to JavaScript extension. After we added these two files we should set their “Copy to Output Directory” property to “Copy Always”, or “Copy if Newer”. Otherwise they will not be involved in the package when deployed. Let’s paste a very simple Node.js code in the “index.js” as below. As you can see I created a web server listening at port 12345. 1: var http = require("http"); 2: var port = 12345; 3:  4: http.createServer(function (req, res) { 5: res.writeHead(200, { "Content-Type": "text/plain" }); 6: res.end("Hello World\n"); 7: }).listen(port); 8:  9: console.log("Server running at port %d", port); Then we need to start “node.exe” with this file when our worker role was started. This can be done in its Run method. I found the Node.js and entry JavaScript file name, and then create a new process to run it. Our worker role will wait for the process to be exited. If everything is OK once our web server was opened the process will be there listening for incoming requests, and should not be terminated. The code in worker role would be like this. 1: public override void Run() 2: { 3: // This is a sample worker implementation. Replace with your logic. 4: Trace.WriteLine("NodejsHost entry point called", "Information"); 5:  6: // retrieve the node.exe and entry node.js source code file name. 7: var node = Environment.ExpandEnvironmentVariables(@"%RoleRoot%\approot\node.exe"); 8: var js = "index.js"; 9:  10: // prepare the process starting of node.exe 11: var info = new ProcessStartInfo(node, js) 12: { 13: CreateNoWindow = false, 14: ErrorDialog = true, 15: WindowStyle = ProcessWindowStyle.Normal, 16: UseShellExecute = false, 17: WorkingDirectory = Environment.ExpandEnvironmentVariables(@"%RoleRoot%\approot") 18: }; 19: Trace.WriteLine(string.Format("{0} {1}", node, js), "Information"); 20:  21: // start the node.exe with entry code and wait for exit 22: var process = Process.Start(info); 23: process.WaitForExit(); 24: } Then we can run it locally. In the computer emulator UI the worker role started and it executed the Node.js, then Node.js windows appeared. Open the browser to verify the website hosted by our worker role. Next let’s deploy it to azure. But we need some additional steps. First, we need to create an input endpoint. By default there’s no endpoint defined in a worker role. So we will open the role property window in Visual Studio, create a new input TCP endpoint to the port we want our website to use. In this case I will use 80. Even though we created a web server we should add a TCP endpoint of the worker role, since Node.js always listen on TCP instead of HTTP. And then changed the “index.js”, let our web server listen on 80. 1: var http = require("http"); 2: var port = 80; 3:  4: http.createServer(function (req, res) { 5: res.writeHead(200, { "Content-Type": "text/plain" }); 6: res.end("Hello World\n"); 7: }).listen(port); 8:  9: console.log("Server running at port %d", port); Then publish it to Windows Azure. And then in browser we can see our Node.js website was running on WACS worker role. We may encounter an error if we tried to run our Node.js website on 80 port at local emulator. This is because the compute emulator registered 80 and map the 80 endpoint to 81. But our Node.js cannot detect this operation. So when it tried to listen on 80 it will failed since 80 have been used.   Use NPM Modules When we are using WAWS to host Node.js, we can simply install modules we need, and then just publish or upload all files to WAWS. But if we are using WACS worker role, we have to do some extra steps to make the modules work. Assuming that we plan to use “express” in our application. Firstly of all we should download and install this module through NPM command. But after the install finished, they are just in the disk but not included in the worker role project. If we deploy the worker role right now the module will not be packaged and uploaded to azure. Hence we need to add them to the project. On solution explorer window click the “Show all files” button, select the “node_modules” folder and in the context menu select “Include In Project”. But that not enough. We also need to make all files in this module to “Copy always” or “Copy if newer”, so that they can be uploaded to azure with the “node.exe” and “index.js”. This is painful step since there might be many files in a module. So I created a small tool which can update a C# project file, make its all items as “Copy always”. The code is very simple. 1: static void Main(string[] args) 2: { 3: if (args.Length < 1) 4: { 5: Console.WriteLine("Usage: copyallalways [project file]"); 6: return; 7: } 8:  9: var proj = args[0]; 10: File.Copy(proj, string.Format("{0}.bak", proj)); 11:  12: var xml = new XmlDocument(); 13: xml.Load(proj); 14: var nsManager = new XmlNamespaceManager(xml.NameTable); 15: nsManager.AddNamespace("pf", "http://schemas.microsoft.com/developer/msbuild/2003"); 16:  17: // add the output setting to copy always 18: var contentNodes = xml.SelectNodes("//pf:Project/pf:ItemGroup/pf:Content", nsManager); 19: UpdateNodes(contentNodes, xml, nsManager); 20: var noneNodes = xml.SelectNodes("//pf:Project/pf:ItemGroup/pf:None", nsManager); 21: UpdateNodes(noneNodes, xml, nsManager); 22: xml.Save(proj); 23:  24: // remove the namespace attributes 25: var content = xml.InnerXml.Replace("<CopyToOutputDirectory xmlns=\"\">", "<CopyToOutputDirectory>"); 26: xml.LoadXml(content); 27: xml.Save(proj); 28: } 29:  30: static void UpdateNodes(XmlNodeList nodes, XmlDocument xml, XmlNamespaceManager nsManager) 31: { 32: foreach (XmlNode node in nodes) 33: { 34: var copyToOutputDirectoryNode = node.SelectSingleNode("pf:CopyToOutputDirectory", nsManager); 35: if (copyToOutputDirectoryNode == null) 36: { 37: var n = xml.CreateNode(XmlNodeType.Element, "CopyToOutputDirectory", null); 38: n.InnerText = "Always"; 39: node.AppendChild(n); 40: } 41: else 42: { 43: if (string.Compare(copyToOutputDirectoryNode.InnerText, "Always", true) != 0) 44: { 45: copyToOutputDirectoryNode.InnerText = "Always"; 46: } 47: } 48: } 49: } Please be careful when use this tool. I created only for demo so do not use it directly in a production environment. Unload the worker role project, execute this tool with the worker role project file name as the command line argument, it will set all items as “Copy always”. Then reload this worker role project. Now let’s change the “index.js” to use express. 1: var express = require("express"); 2: var app = express(); 3:  4: var port = 80; 5:  6: app.configure(function () { 7: }); 8:  9: app.get("/", function (req, res) { 10: res.send("Hello Node.js!"); 11: }); 12:  13: app.get("/User/:id", function (req, res) { 14: var id = req.params.id; 15: res.json({ 16: "id": id, 17: "name": "user " + id, 18: "company": "IGT" 19: }); 20: }); 21:  22: app.listen(port); Finally let’s publish it and have a look in browser.   Use Windows Azure SQL Database We can use Windows Azure SQL Database (a.k.a. WACD) from Node.js as well on worker role hosting. Since we can control the version of Node.js, here we can use x64 version of “node-sqlserver” now. This is better than if we host Node.js on WAWS since it only support x86. Just install the “node-sqlserver” module from NPM, copy the “sqlserver.node” from “Build\Release” folder to “Lib” folder. Include them in worker role project and run my tool to make them to “Copy always”. Finally update the “index.js” to use WASD. 1: var express = require("express"); 2: var sql = require("node-sqlserver"); 3:  4: var connectionString = "Driver={SQL Server Native Client 10.0};Server=tcp:{SERVER NAME}.database.windows.net,1433;Database={DATABASE NAME};Uid={LOGIN}@{SERVER NAME};Pwd={PASSWORD};Encrypt=yes;Connection Timeout=30;"; 5: var port = 80; 6:  7: var app = express(); 8:  9: app.configure(function () { 10: app.use(express.bodyParser()); 11: }); 12:  13: app.get("/", function (req, res) { 14: sql.open(connectionString, function (err, conn) { 15: if (err) { 16: console.log(err); 17: res.send(500, "Cannot open connection."); 18: } 19: else { 20: conn.queryRaw("SELECT * FROM [Resource]", function (err, results) { 21: if (err) { 22: console.log(err); 23: res.send(500, "Cannot retrieve records."); 24: } 25: else { 26: res.json(results); 27: } 28: }); 29: } 30: }); 31: }); 32:  33: app.get("/text/:key/:culture", function (req, res) { 34: sql.open(connectionString, function (err, conn) { 35: if (err) { 36: console.log(err); 37: res.send(500, "Cannot open connection."); 38: } 39: else { 40: var key = req.params.key; 41: var culture = req.params.culture; 42: var command = "SELECT * FROM [Resource] WHERE [Key] = '" + key + "' AND [Culture] = '" + culture + "'"; 43: conn.queryRaw(command, function (err, results) { 44: if (err) { 45: console.log(err); 46: res.send(500, "Cannot retrieve records."); 47: } 48: else { 49: res.json(results); 50: } 51: }); 52: } 53: }); 54: }); 55:  56: app.get("/sproc/:key/:culture", function (req, res) { 57: sql.open(connectionString, function (err, conn) { 58: if (err) { 59: console.log(err); 60: res.send(500, "Cannot open connection."); 61: } 62: else { 63: var key = req.params.key; 64: var culture = req.params.culture; 65: var command = "EXEC GetItem '" + key + "', '" + culture + "'"; 66: conn.queryRaw(command, function (err, results) { 67: if (err) { 68: console.log(err); 69: res.send(500, "Cannot retrieve records."); 70: } 71: else { 72: res.json(results); 73: } 74: }); 75: } 76: }); 77: }); 78:  79: app.post("/new", function (req, res) { 80: var key = req.body.key; 81: var culture = req.body.culture; 82: var val = req.body.val; 83:  84: sql.open(connectionString, function (err, conn) { 85: if (err) { 86: console.log(err); 87: res.send(500, "Cannot open connection."); 88: } 89: else { 90: var command = "INSERT INTO [Resource] VALUES ('" + key + "', '" + culture + "', N'" + val + "')"; 91: conn.queryRaw(command, function (err, results) { 92: if (err) { 93: console.log(err); 94: res.send(500, "Cannot retrieve records."); 95: } 96: else { 97: res.send(200, "Inserted Successful"); 98: } 99: }); 100: } 101: }); 102: }); 103:  104: app.listen(port); Publish to azure and now we can see our Node.js is working with WASD through x64 version “node-sqlserver”.   Summary In this post I demonstrated how to host our Node.js in Windows Azure Cloud Service worker role. By using worker role we can control the version of Node.js, as well as the entry code. And it’s possible to do some pre jobs before the Node.js application started. It also removed the IIS and IISNode limitation. I personally recommended to use worker role as our Node.js hosting. But there are some problem if you use the approach I mentioned here. The first one is, we need to set all JavaScript files and module files as “Copy always” or “Copy if newer” manually. The second one is, in this way we cannot retrieve the cloud service configuration information. For example, we defined the endpoint in worker role property but we also specified the listening port in Node.js hardcoded. It should be changed that our Node.js can retrieve the endpoint. But I can tell you it won’t be working here. In the next post I will describe another way to execute the “node.exe” and Node.js application, so that we can get the cloud service configuration in Node.js. I will also demonstrate how to use Windows Azure Storage from Node.js by using the Windows Azure Node.js SDK.   Hope this helps, Shaun All documents and related graphics, codes are provided "AS IS" without warranty of any kind. Copyright © Shaun Ziyan Xu. This work is licensed under the Creative Commons License.

    Read the article

< Previous Page | 1 2 3 4  | Next Page >