Search Results

Search found 32 results on 2 pages for 'xpathnavigator'.

Page 1/2 | 1 2  | Next Page >

  • XPathNavigator in Silverlight

    - by vladimir
    I have a code library that makes heavy use of XPathNavigator to parse some specific xml document. The xml document is cross-referenced, meaning that an element can reference another which has not yet been encountered during parsing: <ElementA ...> <DependentElementX id="1234"> </ElementA> <ElementX id="1234" .../> The document doesn't really look like this, but the point is that 1) there is an xml schema that enforces the overall document structure, 2) elements inside the document can reference each other using some IDs, and 3) there is quite a few such cross references between different elements in the document. The document is parsed in two phases. In the first pass I walk through the document XPathDocument doc = ...; XPathNavigator nav = doc.CreateNavigator(); nav.MoveToRoot(); nav.MoveToFirstChild()... and occasionally 'bookmark' the current position (element) in the document using XPathNavigator.Clone() method. This gives me a lightweight instance of an XPathNavigator which I can store somewhere and use later to jump back to a particular place (element) in my document. Once I have enough information collected in the first pass (for example, I have made sure there is indeed an ElementX with an id='1234'), I jump back to saved bookmarks (using those saved XPathNavigators) and complete the parsing. Well, now I'm about to use this library in Silverlight 3.0 and to my horror the XPathNavigator is not in the System.Xml assembly. Questions: 1) Am I missing something obvious (i.e. XPathNavigator does exist in some shape or form, for example in a toolkit or a freeware library)? 2) If I do have to make modifications in the code, what would be the best way to go? Ideally, I would like to make minimal changes, not to rewrite 80% of the code just to be able to use something like XLinq. To resume, in case I have to give up XPathNavigator, all I need is a way to bookmark places in my document and to get back to them so that I can continue to iterate from where I left off. Thanks in advance for any help/ideas.

    Read the article

  • Need Help About Using XPathNavigator in C#?

    - by Nano HE
    Hello. My XML file as below. It mixed schema and normal elements. <?xml version="1.0" encoding="utf-8"?> <!-- R1 --> <ax:root xmlns:ax="http://amecn/software/realtime/ax"> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="EquipmentConstants"> <xsd:complexType> <xsd:sequence> <xsd:element minOccurs="0" maxOccurs="unbounded" ref="EquipmentConstant" /> </xsd:sequence> </xsd:complexType> <xsd:unique name="id"> <xsd:selector xpath=".//EquipmentConstant" /> <xsd:field xpath="@id" /> </xsd:unique> </xsd:element> ...... ...... </xsd:schema> <EquipmentConstants xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <EquipmentConstant id="0"> <Name>SerialNumber</Name> <Group>SYSTEM</Group> <Data> <Value min="0" max="10000000" scale_factor="0" unit="U_NO_UNITS" permission="NolimitedAndNoChangeable" type="xsd_string" enum="" flag="0">0</Value> </Data> <Description>Serial Number</Description> </EquipmentConstant> ..... ..... </EquipmentConstants> </ax:root> My C# code as below. I want to loop the elements from <EquipmentConstants xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> XPathDocument doc = new XPathDocument("test.xml"); XPathNavigator navigator = doc.CreateNavigator(); navigator.MoveToRoot(); // <?xml version="1.0" encoding="utf-8"?> //navigator.MoveToFirstChild(); // <!-- R1 --> // 1st, I tried to use MoveToChield(), But I failed to move there. navigator.MoveToChild("EquipmentConstants"); // Then, I also tried to use SelectSingleNode(). But I failed too. navigator.SelectSingleNode("ax/EquipmentConstants"); while (navigator.MoveToNext()) { // do something. } Could you please give me some suggestion. Thank you.

    Read the article

  • XPathNavigator.Evaluate returning incorrect value?

    - by Eric
    I'm expecting this code to return true but it doesn't ? What am I missing here. string xml = @"<data><e id=""NUM_CPUS"">1</e><e id=""ACE_PRESENT"">1</e></data>"; XPathDocument doc = new XPathDocument(new StringReader(xml)); string expr = "(id('NUM_CPUS'))>=1 and (id('ACE_PRESENT'))=1"; XPathNavigator nav = doc.CreateNavigator(); XPathExpression query = nav.Compile(expr); object result = nav.Evaluate(query); bool b = bool.Parse(result.ToString()); if (!b) throw new Exception("Should be true");

    Read the article

  • How to avoid avoid linebreaks and spaces for XmlWellFormedWriter

    - by user302670
    Hi, i am getting an XmlWriter of the AppendChild() method of a xPathNavigator. using (XmlWriter writer = xPathNavigator.AppendChild()) { writer.WriteStartAttribute("name"); writer.WriteEndElement(); } The AppendChild() method returns a instance of XmlWellFormedWriter. I want to avoid linebreaks and spaces in my output xml. But the XmlWriterSettings are readonly and using an wrapper does not help anything. I tried this, but the setting of nether the wrapper nor the writer changes: XmlWriterSettings settings = new XmlWriterSettings(); settings.IndentChars = ""; settings.NewLineChars = ""; using (XmlWriter wrapper = xPathNavigator.AppendChild()) { XmlWriter writer = XmlWriter.Create(writer, settings); writer.WriteStartAttribute("name"); writer.WriteEndElement(); } Does anybody has an idea what todo? Thanks!

    Read the article

  • Using Xpath With Default Namespace in C#

    - by macleojw
    I've got an XML document with a default namespace. I'm using a XPathNavigator to select a set of nodes using Xpath as follows: XmlElement myXML = ...; XPathNavigator navigator = myXML.CreateNavigator(); XPathNodeIterator result = navigator.Select("/outerelement/innerelement"); I am not getting any results back: I'm assuming this is because I am not specifying the namespace. How can I include the namespace in my select?

    Read the article

  • Can I get an XPathNodeIterator directly from an XPath?

    - by Val
    I hope I'm just missing something obvious. I have a number of repeating nodes in an XML document: <root> <parent> <child/> <child/> </parent> </root> I need to examine the contents of each of the <child> elements in turn, so I need an XPathNodeIterator containing the nodeset of all the <child> nodes. If I have an XPath that would select the child nodes, e.g. /root/parent/child, is there any way to feed that directly to a new XPathNodeIterator? Everything I see in the docs and examples indicates I have to first get an XPathNavigator to the <parent>, then Select the child nodes, like: XPathNavigator nav = datasource.CreateNavigator().SelectSingleNode( "/root/parent" ); XPathNodeIterator it = nav.Select( "./child" ); foreach ( child in it ) { /* do something */ } I was hoping to skip the XPathNavigator, and intialize the XPathNodeIterator with XPath to the child nodes directly, something like: XpathNodeIterator it = new XpathNodeIterator("/root/parent/child"); foreach ( child in it ) { /* do something */ } Possible? The benefit is not only saving a line of code, but I can use a single XPath expression, rather than splitting the path to the <child> nodes in two, first to get the parent element, then to select its children.

    Read the article

  • problem with AddSort method

    - by netNewbi3
    Hi Could you let me know what the proboem is with sorting in this code? It doesn't work. My xml: CONTRACTS --CONTRACT ---SUPPLIER ---COMMODITIES ----COMMODITY -----COMODDITYNAME My code: Dim myString As StringBuilder = New StringBuilder(200) Dim xdoc As New XPathDocument("local_xml.xml") Dim nav As XPathNavigator = xdoc.CreateNavigator() Dim expr As XPathExpression expr = nav.Compile("/pf:CONTRACTS/pf:CONTRACT") Dim namespaceManager As XmlNamespaceManager = New XmlNamespaceManager(nav.NameTable) namespaceManager.AddNamespace("pf", "http://namespace.ac.uk/") expr.AddSort("pf:SUPPLIER", XmlSortOrder.Ascending, XmlCaseOrder.None, String.Empty, XmlDataType.Text) expr.SetContext(namespaceManager) Dim nodes As XPathNodeIterator = nav.Select(expr) If nodes.Count > 0 Then myString.AppendLine("<table width='96%' border='0' cellpadding='0' cellspacing='0' border='0' class='datatable1'>") myString.AppendLine("<th width='35%'>Name</th><th width='35%'>Commodity</th><th width='20%'>Supplier</a></th>") While nodes.MoveNext() Dim node As XPathNavigator = nodes.Current.SelectSingleNode("pf:NAME", namespaceManager) Dim supplier As XPathNavigator = nodes.Current.SelectSingleNode("pf:SUPPLIER", namespaceManager) Dim commodity As XPathNavigator = nodes.Current.SelectSingleNode("pf:COMMODITIES/pf:COMMODITY/pf:COMMODITYNAME", namespaceManager) Dim sChars As String = " " myString.AppendLine("<tr>") myString.AppendLine("<td>") myString.AppendLine(node.ToString()) myString.AppendLine("</td>") myString.AppendLine("<td>") myString.AppendLine(commodity.ToString()) myString.AppendLine("</td>") myString.AppendLine("<td>") myString.AppendLine(supplier.ToString()) myString.AppendLine("</td>") myString.AppendLine("</tr>") End While myString.AppendLine("</table>") Dim strOutput As String = myString.ToString() lblOutput.Text = strOutput Else lblOutput.Text = "No results for your search<br/>" End If

    Read the article

  • Error Installing COM+ (Error Code: 80131501)

    - by Regina Foo
    I've written a class library that reads from an xml file and return the result as a string. But when I want to install it as a COM+ component, an error occurred (Error Code: 80131501). I checked the event log and the details of the error is: Installation of 'C:\Users\User\Documents\Visual Studio 2005\Projects\InteropSOA\InteropSOA\bin\Debug\InteropSOA.dll' into '{28E82165-AD74-4E16-90C9-0C5CE7DA97AA}' failed with an exception: System.EnterpriseServices.RegistrationException: FATAL: Could not find component 'InteropSOA.ConfigReader' we just installed. at System.EnterpriseServices.RegistrationDriver.InstallAssembly(RegistrationConfig regConfig, Object obSync) at System.EnterpriseServices.RegistrationHelper.InstallAssemblyFromConfig(RegistrationConfig& regConfig) at System.EnterpriseServices.RegistrationHelper.InstallAssembly(String assembly, String& application, String partition, String& tlb, InstallationFlags installFlags) at System.EnterpriseServices.Internal.ComManagedImportUtil.InstallAssembly(String asmpath, String parname, String appname) Below are the steps I've done while developing the class library: Added "System.EnterpriseServices" to Reference. Imported the reference to the class. Declared the class as "ServicedComponent". Set project properties ("Make assembly COM-visible" checked, "Register for COM Interop" checked, Signed the assembly with a strong key file name.) Here are my codes: using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.XPath; using System.EnterpriseServices; namespace InteropSOA { public class ConfigReader : ServicedComponent { // xml file name private string strFileName; // type of request private string strRequest = ""; // response string private string strResponse = ""; // declarations for xPath private XPathDocument doc; private XPathNavigator nav; private XPathExpression expr; private XPathNodeIterator iterator; private XmlTextReader reader; private XmlDocument xmlDoc; public ConfigReader(string strFile, string request) { this.strFileName = strFile; this.strRequest = request; } public ConfigReader() { //default contructor } // reader for console program public void ReadXML() { doc = new XPathDocument(strFileName); nav = doc.CreateNavigator(); // compile xPath expression expr = nav.Compile("/Msg/" + strRequest + "/*"); iterator = nav.Select(expr); // interate on the node set try { while (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); strResponse += nav2.Value + "|"; } } catch (Exception ex) { Console.WriteLine(ex.Message); } strResponse = strResponse.Substring(0, strResponse.Length-1); Console.WriteLine("Response string = " + strResponse); } public void WriteXML(string strRequest, string strElement, string strValue) { reader = new XmlTextReader(strFileName); xmlDoc = new XmlDocument(); xmlDoc.Load(reader); reader.Close(); XmlNode node; XmlElement root = xmlDoc.DocumentElement; node = root.SelectSingleNode("/Msg/" + strRequest + "/" + strElement); node.InnerText = strValue; xmlDoc.Save(strFileName); } // reader for ASP.NET public string ReadXMLElement() { doc = new XPathDocument(strFileName); nav = doc.CreateNavigator(); // compile xPath expression expr = nav.Compile("/Msg/" + strRequest + "/*"); iterator = nav.Select(expr); // interate on the node set try { while (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); strResponse += nav2.Value + "|"; } } catch (Exception ex) { Console.WriteLine(ex.Message); } strResponse = strResponse.Substring(0, strResponse.Length - 1); return strResponse; } } }

    Read the article

  • Delete / Remove node from XPathNodeIterator, given an XPath

    - by RymdPung
    First of all, if someone has a different, perhaps shorter (or better), solution to the problem, it's welcome as well. I'm trying to "simply" remove (almost) duplicate elements in XSLT. There's some (metadata) nodes i don't want to include when comparing, and i couldn't figure out how do do that in XSLT so thought i'd extend it with a function removing these nodes. Like so: <xsl:for-each select="abx:removeNodes(d/df600|d/df610|d/df611|d/df630|d/df650|d/df651|d/df655, '*[@key=&quot;i1&quot; or @key=&quot;i2&quot; or key=&quot;db&quot;]')"> <xsl:if test="not(node()=preceding-sibling::*)"> blah </xsl:if> </xsl:for-each> And the extension, which doesn't work so well... (C#) public XPathNodeIterator removeNodes(XPathNodeIterator p_NodeIterator, String removeXPath) { Logger Logger = new Logger("xslt"); Logger.Log("removeNodes(removeXPath={0}):", removeXPath); foreach (XPathNavigator CurrentNode in p_NodeIterator) { Logger.Log("removeNodes(): CurrentNode.OuterXml={0}.", CurrentNode.OuterXml); foreach (XPathNavigator CurrentSubNode in CurrentNode.Select(removeXPath)) { Logger.Log("removeNodes(): CurrentSubNode.OuterXml={0}.", CurrentSubNode.OuterXml); // How do i delete this node!? //CurrentSubNode.DeleteSelf(); } } return p_NodeIterator; } My initial approach using 'CurrentSubNode.DeleteSelf();' doesn't work because it gets confused and loses its position in the XPathNavigator, causing it to only delete the first item it finds using "removeXPath". Something like a DeleteAndMoveNext() would be nice but there seems to be no such method... Example data: <df650> <df650 key="i1"> </df650> <df650 key="i2">0</df650> <df650 key="a">foo</df650> <df650 key="x">bar</df650> <df650 key="db">someDB</df650> <df650 key="id">b2</df650> <df650 key="dsname">someDS</df650> </df650> ..and then another identical node (if you ignore the meta fields; db,id,dsname). <df650> <df650 key="i1"> </df650> <df650 key="i2">0</df650> <df650 key="a">foo</df650> <df650 key="x">bar</df650> <df650 key="db">someOtherDB</df650> <df650 key="id">b2</df650> <df650 key="dsname">someOtherDS</df650> </df650> The result should be... <df650> <df650 key="i1"> </df650> <df650 key="i2">0</df650> <df650 key="a">foo</df650> <df650 key="x">bar</df650> </df650>

    Read the article

  • Problem in SharePoint Object model when accessing the sharepoint list items?

    - by JanardhanReddy
    just i wrote using (SPSite site = SPContext.Current.Site) { using (SPWeb web = site.OpenWeb()) { //SPList lst = web.Lists["ManagerInfo"]; SPList lst = web.Lists[strlist]; SPQuery getUserNameQuery = new SPQuery(); // getUserNameQuery.Query = "<Where><And><Eq><FieldRef Name=\"Region\" /><Value Type=\"Text\">" + strRegion + "</Value></Eq><And><Eq><FieldRef Name=\"PM_x0020_First_x0020_Name\" /><Value Type=\"Text\">" + pmFName + "</Value></Eq><Eq><FieldRef Name=\"PM_x0020_Last_x0020_Name\" /><Value Type=\"Text\">" + pmLname + "</Value></Eq></And></And></Where>"; // getUserNameQuery.Query = "<Where><And><Eq><FieldRef Name=\"PM_x0020_First_x0020_Name\" /><Value Type=\"Text\">" + pmFName + "</Value></Eq><Eq><FieldRef Name=\"PM_x0020_Last_x0020_Name\" /><Value Type=\"Text\">" + pmLname + "</Value></Eq></And></Where>"; getUserNameQuery.Query = "<Where><Eq><FieldRef Name=\"PM_x0020_Name\" /><Value Type=\"Text\">" + loginName + "</Value></Eq></Where>"; SPListItemCollection items = lst.GetItems(getUserNameQuery); foreach (SPListItem item in items) { managerFName = item["Manager Name"].ToString(); strAccounting = item["Accounting"].ToString(); managerFName = managerFName.Replace(".", " "); strAccounting = strAccounting.Replace(".", " "); // isFound = true; XPathNavigator managerName = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtManagerName", NamespaceManager); managerName.SetValue(managerFName); XPathNavigator accountingName = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtAccountingName", NamespaceManager); accountingName.SetValue(strAccounting); } } } i used this code in infopath this infopath is using by all users.os when the current login user have no permissions to the list it showing error.when the current login user have full Permission it is working. So Please advise me what can i do inorder to work them for all users.

    Read the article

  • Searching in XML using Xpath

    - by Sathish
    I have an XML file like below , using xpath and xnavigator how can get the Value of the supplied Tag Attribute for example if i supply RangeName i should get AssumptClient <Validations> <FieldInfo id="1"> <Name>OMID</Name> <Mandatory>Yes</Mandatory> <RangeName>AssumptOMID</RangeName> <DataType>int</DataType> <MaxLength>10</MaxLength> </FieldInfo> <FieldInfo id="2"> <Name>ClientName</Name> <Mandatory>Yes</Mandatory> <RangeName>AssumptClient</RangeName> <DataType>string</DataType> <MaxLength>50</MaxLength> </FieldInfo> <FieldInfo id="3"> <Name>OppName</Name> <Mandatory>Yes</Mandatory> <RangeName>AssumptProjectName</RangeName> <DataType>string</DataType> <MaxLength>50</MaxLength> </FieldInfo> <FieldInfo id="4"> <Name>OperatingGroup</Name> <Mandatory>Yes</Mandatory> <RangeName>AssumptOperatingGroup</RangeName> <DataType>string</DataType> <MaxLength>50</MaxLength> </FieldInfo> </Validations> for now i am using the below code XPathDocument doc; XPathNavigator nav; XPathExpression expr; XPathNodeIterator iterator; doc = new XPathDocument(strConfigFile); nav = doc.CreateNavigator(); expr = nav.Compile("/configuration/Validations/FieldInfo[RangeName='AssumptClient']"); iterator = nav.Select(expr); if (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); textBox1.Text = nav2.GetAttribute("RangeName", ""); }

    Read the article

  • How to estimate memory need by XPathDocument for a specific xml file

    - by bill seacham
    Is there any way to estimate the memory requirement for creating an XpathDocument instance based on the file size of the xml? XpathDocument xdoc = new XpathDocument(xmlfile); Is there any way to programmatically stop the process of creating the XpathDocument if memory drops to a very low level? Since it loads the entire xml into memory, it would be nice to know ahead of time if the xml is too big. What I have found is that when I create a new XpathDocument with a big xml file, an outofmemory exception is never fired, but that the process slows to a crawl, only 5 Mb of memory remains a available and the Task Manager reports it is not responding. This happened with a 266 Mb xml file when there was 584 Mb of ram. I was able to load a 150 Mb file with no problems in 18. After loading the xml, I want to do xpath queries using an XpathNavigator and an XpathNodeIterator. I am using .net 2.0, xp sp3.

    Read the article

  • Retrieving xml value into a string

    - by DelvinK
    Hello, In the following XML structure how do i retrieve the name value and put this into a string? (i am using a XPathNavigator in my method) <testsystem> <test> <name>one</name> </test> </testsystem> I was able to get a attribute with a syntax alike this: (but when changing the xml struture it no longer holds a attribute value) string name = nav.GetAttribute("name", "") But have no luck getting the value with a nav as of yet. The purpose is to be able to use it for the following object so i can put name into it. test t = new test() { Name = name, Questions= new List<Questions>() }; Best regards.

    Read the article

  • Parse XML document

    - by Neil
    I am trying to parse a remote XML document (from Amazon AWS): <ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2009-03-31"> <OperationRequest> <RequestId>011d32c5-4fab-4c7d-8785-ac48b9bda6da</RequestId> <Arguments> <Argument Name="Condition" Value="New"></Argument> <Argument Name="Operation" Value="ItemLookup"></Argument> <Argument Name="Service" Value="AWSECommerceService"></Argument> <Argument Name="Signature" Value="73l8oLJhITTsWtHxsdrS3BMKsdf01n37PE8u/XCbsJM="></Argument> <Argument Name="MerchantId" Value="Amazon"></Argument> <Argument Name="Version" Value="2009-03-31"></Argument> <Argument Name="ItemId" Value="603084260089"></Argument> <Argument Name="IdType" Value="UPC"></Argument> <Argument Name="AWSAccessKeyId" Value="[myAccessKey]"></Argument> <Argument Name="Timestamp" Value="2010-06-14T15:03:27Z"></Argument> <Argument Name="ResponseGroup" Value="OfferSummary,ItemAttributes"></Argument> <Argument Name="SearchIndex" Value="All"></Argument> </Arguments> <RequestProcessingTime>0.0318510000000000</RequestProcessingTime> </OperationRequest> <Items> <Request> <IsValid>True</IsValid> <ItemLookupRequest> <Condition>New</Condition> <DeliveryMethod>Ship</DeliveryMethod> <IdType>UPC</IdType> <MerchantId>Amazon</MerchantId> <OfferPage>1</OfferPage> <ItemId>603084260089</ItemId> <ResponseGroup>OfferSummary</ResponseGroup> <ResponseGroup>ItemAttributes</ResponseGroup> <ReviewPage>1</ReviewPage> <ReviewSort>-SubmissionDate</ReviewSort> <SearchIndex>All</SearchIndex> <VariationPage>All</VariationPage> </ItemLookupRequest> </Request> <Item> <ASIN>B0000UTUNI</ASIN> <DetailPageURL>http://www.amazon.com/Garnier-Fructis-Fortifying-Conditioner-Minute/dp/B0000UTUNI%3FSubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB0000UTUNI</DetailPageURL> <ItemLinks> <ItemLink> <Description>Technical Details</Description> <URL>http://www.amazon.com/Garnier-Fructis-Fortifying-Conditioner-Minute/dp/tech-data/B0000UTUNI%3FSubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> <ItemLink> <Description>Add To Baby Registry</Description> <URL>http://www.amazon.com/gp/registry/baby/add-item.html%3Fasin.0%3DB0000UTUNI%26SubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> <ItemLink> <Description>Add To Wedding Registry</Description> <URL>http://www.amazon.com/gp/registry/wedding/add-item.html%3Fasin.0%3DB0000UTUNI%26SubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> <ItemLink> <Description>Add To Wishlist</Description> <URL>http://www.amazon.com/gp/registry/wishlist/add-item.html%3Fasin.0%3DB0000UTUNI%26SubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> <ItemLink> <Description>Tell A Friend</Description> <URL>http://www.amazon.com/gp/pdp/taf/B0000UTUNI%3FSubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> <ItemLink> <Description>All Customer Reviews</Description> <URL>http://www.amazon.com/review/product/B0000UTUNI%3FSubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> <ItemLink> <Description>All Offers</Description> <URL>http://www.amazon.com/gp/offer-listing/B0000UTUNI%3FSubscriptionId%3DAKIAIYPTKHCWTRWWPWBQ%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0000UTUNI</URL> </ItemLink> </ItemLinks> <ItemAttributes> <Binding>Health and Beauty</Binding> <Brand>Garnier</Brand> <EAN>0603084260089</EAN> <Feature>Helps restore strength and shine</Feature> <Feature>Penetrates deep to nourish, repair and rejuvenate</Feature> <Feature>Makes hair softer and more manageable without weighing it down</Feature> <ItemDimensions> <Weight Units="hundredths-pounds">40</Weight> </ItemDimensions> <Label>Garnier</Label> <ListPrice> <Amount>419</Amount> <CurrencyCode>USD</CurrencyCode> <FormattedPrice>$4.19</FormattedPrice> </ListPrice> <Manufacturer>Garnier</Manufacturer> <NumberOfItems>1</NumberOfItems> <ProductGroup>Health and Beauty</ProductGroup> <ProductTypeName>ABIS_DRUGSTORE</ProductTypeName> <Publisher>Garnier</Publisher> <Size>5.0 oz</Size> <Studio>Garnier</Studio> <Title>Garnier Fructis Fortifying Fortifying Deep Conditioner, 3 Minute Masque - 5 oz</Title> <UPC>603084260089</UPC> </ItemAttributes> <OfferSummary> <LowestNewPrice> <Amount>229</Amount> <CurrencyCode>USD</CurrencyCode> <FormattedPrice>$2.29</FormattedPrice> </LowestNewPrice> <TotalNew>7</TotalNew> <TotalUsed>0</TotalUsed> <TotalCollectible>0</TotalCollectible> <TotalRefurbished>0</TotalRefurbished> </OfferSummary> </Item> </Items> </ItemLookupResponse> I am trying to extract data from the XML stream using XPathDocument, but with no luck: WebRequest request = HttpWebRequest.Create(url); WebResponse response = request.GetResponse(); //XmlDocument doc = new XmlDocument(); XPathDocument Doc = new XPathDocument(response.GetResponseStream()); XPathNavigator nav = Doc.CreateNavigator(); XPathNodeIterator ListPrice = nav.Select("/ItemLookupResponse/Items/Item/ItemAttributes/ListPrice"); foreach (XPathNavigator node in ListPrice) { Response.Write(node.GetAttribute("Amount", NAMESPACE)); } What am I missing? Thanks in advance!!

    Read the article

  • BizTalk Testing Series - The xpath Function

    - by Michael Stephenson
    Background While the xpath function in a BizTalk orchestration is a very powerful feature I have often come across the situation where someone has hard coded an xpath expression in an orchestration. If you have read some of my previous posts about testing I've tried to get across the general theme like test-driven or test-assisted development approaches where the underlying principle is that your building up your solution of small well tested units that are put together and the resulting solution is usually quite robust. You will be finding more bugs within your unit tests and fewer outside of your team. The thing I don't like about the xpath functions usual usage is when you come across an orchestration which has something like the below snippet in an expression or assign shape: string result = xpath(myMessage,"string(//Order/OrderItem/ProductName)"); My main issue with this is that the xpath statement is hard coded in the orchestration and you don't really know it works until you are running the orchestration. Some of the problems I think you end up with are: You waste time with lengthy debugging of the orchestration when your statement isn't working You might not know the function isn't working quite as expected because the testable unit around it is big You are much more open to regression issues if your schema changes     Approach to Testing The technique I usually follow is to hold the xpath statement as a constant in a helper class or to format a constant with a helper function to get the actual xpath statement. It is then used by the orchestration like follows. string result = xpath(myMessage, MyHelperClass.ProductNameXPathStatement); This means that because the xpath statement is available outside of the orchestration it now becomes testable in its own right. This means: I can test it in its own right I'm less likely to waste time tracking down problems caused by an error in the statement I can reduce the risk or regression issuess I'm now able to implement some testing around my xpath statements which usually are something like the following:    The test will use a sample xml file The sample will be validated against the schema The test will execute the xpath statement and then check the results are as expected     Walk-through BizTalk uses the XPathNavigator internally behind the xpath function to implement the queries you will usually use using the navigators select or evaluate functions. In the sample (link at bottom) I have a small solution which contains a schema from which I have generated a sample instance. I will then use this instance as the basis for my tests.     In the below diagram you can see the helper class which I've encapsulated my xpath expressions in, and some helper functions which will format the expression in the case of a repeating node which would want to inject an index into the xpath query.             I have then created a test class which has some functions to execute some queries against my sample xml file. An example of this is below.         In the test class I have a couple of helper functions which will execute the xpath expressions in a similar way to BizTalk. You could have a proper helper class to do this if you wanted.         You can see now in the BizTalk expression editor I can use these functions alongside the xpath function.         Conclusion I hope you can see with very little effort you can make your life much easier by testing xpath statements outside of an orchestration rather than using them directly hard coded into the orchestration.     This can also save you lots of pain longer term because your build should break if your schema changes unexpectedly causing these xpath tests to fail where as your tests around the orchestration will be more difficult to troubleshoot and workout the cause of the problem.     Sample Link The sample is available from the following link: http://code.msdn.microsoft.com/testbtsxpathfunction     Other Tools On the subject of using the xpath function, if you don't already use it the below tool is very useful for creating your xpath statements (thanks BizBert) http://www.bizbert.com/bizbert/2007/11/30/XPath+The+Hidden+Language+Of+BizTalk.aspx

    Read the article

  • How to migrate from XslTransform to XslCompiledTransform

    - by Atara
    I have the following code that I need to migrate from VS 2003 (.Net 1.1) to VS 2008 (.Net 2+) but I get compilation error - System.Xml.Xsl.XslTransform' is obsolete: This class has been deprecated. I probably need to use System.Xml.Xsl.XslCompiledTransform instead. but I do not find the matching Load() and Transform() overload versions that I can use with all the parameters of my original code. in MSDN [How to: Migrate Your XslTransform Code] I only found some simpler cases. http://msdn.microsoft.com/en-us/library/aa983475%28VS.80%29.aspx but in my code I see some remarks that hints that the added parameters were used to avoid exceptions, so I prefer to use these parameters. Can someone please help migrating this code? Thanks, Atara ' ---------------------------------------------------------------------- ' VS 2003 code: ' ---------------------------------------------------------------------- . . . Dim myXslDoc As Xml.XmlDocument ' ---------------------------------------------------------------------- Public Sub mcSetParameters(ByVal srcFileName As String) ' ---------------------------------------------------------------------- Me.myXslDoc = New Xml.XmlDocument Me.myXslDoc.Load(srcFileName) End Sub ' ---------------------------------------------------------------------- Public Sub mcSetHtml() ' ---------------------------------------------------------------------- Dim oXPathNav As System.Xml.XPath.XPathNavigator = xmlDoc.DocumentElement.CreateNavigator() Dim sbContent As New System.Text.StringBuilder Dim swContent As New System.IO.StringWriter(sbContent) Dim args As New System.Xml.Xsl.XsltArgumentList args.AddParam("paramName1", "", paramVal1.ToString) args.AddParam("paramName2", "", paramVal2.ToString) Try ' Try to avoid "Invalid site" exception, by using XmlUrlResolver and Evidence. ' If the XSLT stylesheet . . . comes from a code base that you trust, Then use Me.GetType().Assembly.Evidence() Dim resolver As System.Xml.XmlUrlResolver = New System.Xml.XmlUrlResolver resolver.Credentials = System.Net.CredentialCache.DefaultCredentials Dim xslt As System.Xml.Xsl.XslTransform = New System.Xml.Xsl.XslTransform xslt.Load(Me.myXslDoc, resolver, Me.GetType().Assembly.Evidence()) xslt.Transform(oXPathNav, args, swContent, Nothing) Catch ex As Exception Debug.WriteLine("Exception: {0}", ex.ToString()) End Try DoSomething(sbContent.ToString()) End Sub ' ----------------------------------------------------------------------

    Read the article

  • Problem with XElement and XslCompiledTransform

    - by Graham Clark
    I'm having some trouble using a combination of XElement and XslCompiledTransform. I've put the sample code I'm using below. If I get my input XML using the GetXmlDocumentXml() method, it works fine. If I use the GetXElementXml() method instead, I get an InvalidOperationException when calling the Transform method of XslComiledTransform: Token Text in state Start would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment. The CreateNavigator method on both XElement and XmlDocument returns an XPathNavigator. What extra stuff is XmlDocument doing so this all works, and how can I do the same with XElement? Am I just doing something insane? static void Main(string[] args) { XslCompiledTransform stylesheet = GetStylesheet(); // not shown for brevity IXPathNavigable input = this.GetXElementXml(); using (MemoryStream ms = this.TransformXml(input, stylesheet)) { XmlReader xr = XmlReader.Create(ms); xr.MoveToContent(); } } private MemoryStream TransformXml( IXPathNavigable xml, XslCompiledTransform stylesheet) { MemoryStream transformed = new MemoryStream(); XmlWriter writer = XmlWriter.Create(transformed); stylesheet.Transform(xml, null, writer); transformed.Position = 0; return transformed; } private IXPathNavigable GetXElementXml() { var xml = new XElement("x", new XElement("y", "sds")); return xml.CreateNavigator(); } private IXPathNavigable GetXmlDocumentXml() { var xml = new XmlDocument(); xml.LoadXml("<x><y>sds</y></x>"); return xml.CreateNavigator(); }

    Read the article

  • Infopath - Repeating sections

    - by witsEnd
    I have struggled with this for 2 days and posted this question at a couple of other sites but with no luck. I am creating a form as follows. I have an "outer" repeating section in which the user enters a work item id and then selects as many names as he/she wishes from a series of drop down lists. When the user clicks a button (also in this "outer" repeating section), Feedback textboxes are added for each name selected, as well as text boxes with the names selected from the drop down appear above the those provided for feedback. I used the XPathNavigator.Clone() method to create the new feedback textboxes and textboxes that display the user's name that was selected. (The username textbox appears above the respective feedback textbox). This did the trick, but there is a problem. The user should be able to click "Insert item" on the outer repeating section to add another work item wherein he/she may again select as many names as they wish from the series of drop downs, click a button, and have feedback and user name text boxes appear for each name selected from the drop down box associated with the current work item, (i.e, "outer" repeating section). I clicked Insert Item on the "outer" repeating section and selected 2 names from the second series of drop downs, but when I try to clone a node, it is added at the end of the previous repeating section. I don't know how to navigate into (for lack of a better term) subsequent repeating sections. I am using InfoPath 2007 and I am aware that the current() method call is implicit, but this still doesn't work. I'm thinking I need to set up a Rule somewhere, but I am not sure how to do that. Any help would be appreciated.

    Read the article

  • How do I see items embedded/attached to my Gallio test log in CruiseControl.NET?

    - by GraemeF
    I can use the following code to attach a log file to my Gallio 3.2 acceptance test report: TestLog.AttachPlainText("Attached log file", File.ReadAllText(path)); When I run my tests locally I can see the log file contents by viewing the report in my web browser. However, if I run the tests under CCNET 1.4.4 I get the following error when I try to browse to an attached file in the report via the web dashboard: Exception Message The attachment was not inlined into the XML report. Exception Full Details System.InvalidOperationException: The attachment was not inlined into the XML report. at CCNet.Gallio.WebDashboard.Plugin.GallioAttachmentBuildAction.CreateResponseFromAttachment(XPathNavigator attachmentNavigator) at CCNet.Gallio.WebDashboard.Plugin.GallioAttachmentBuildAction.Execute(ICruiseRequest cruiseRequest) at ThoughtWorks.CruiseControl.WebDashboard.MVC.Cruise.ServerCheckingProxyAction.Execute(ICruiseRequest cruiseRequest) at ThoughtWorks.CruiseControl.WebDashboard.MVC.Cruise.BuildCheckingProxyAction.Execute(ICruiseRequest cruiseRequest) at ThoughtWorks.CruiseControl.WebDashboard.MVC.Cruise.ProjectCheckingProxyAction.Execute(ICruiseRequest cruiseRequest) at ThoughtWorks.CruiseControl.WebDashboard.MVC.Cruise.CruiseActionProxyAction.Execute(IRequest request) at ThoughtWorks.CruiseControl.WebDashboard.MVC.Cruise.CachingActionProxy.Execute(IRequest request) at ThoughtWorks.CruiseControl.WebDashboard.MVC.Cruise.ExceptionCatchingActionProxy.Execute(IRequest request) I get similar results when I try to embed the file instead with: TestLog.EmbedPlainText("Embedded log file", File.ReadAllText(path)); Is it possible to get this working?

    Read the article

  • using xpath get the correct value in selectName

    - by Sangeeta
    Below I have written the code. I need help to get the right value in selectName. I am new to XPath. Basically with this code I am trying to achieve if employeeName = Chris I need to return 23549 to the calling function. Please help. Part of the code: public static string getEmployeeeID(string employeeName) { Cache cache = HttpContext.Current.Cache; string cacheNameEmployee = employeeName + "Tech"; if (cache[cacheNameEpm] == null) { XPathDocument doc = new XPathDocument(HttpContext.Current.Request.MapPath("inc/xml/" + SiteManager.Site.ToString() + "TechToolTip.xml")); XPathNavigator navigator = doc.CreateNavigator(); string selectName = "/Technologies/Technology[FieldName='" + fieldName + "']/EpmId"; XPathNodeIterator nodes = navigator.Select(selectName); if (nodes.Count > 0) { if (nodes.Current.Name.Equals("FieldName")) //nodes.Current.MoveToParent(); //nodes.Current.MoveToParent(); //nodes.Current.MoveToChild("//EpmId"); cache.Add(cacheNameEpm, nodes.Current.Value, null, DateTime.Now + new TimeSpan(4, 0, 0), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null); } } return cache[cacheNameEpm] as string; } XML file <?xml version="1.0" encoding="utf-8" ?> <Employees> <Employee> <EName>Chris</EName> <ID>23556</ID> </Employee> <Employee> <EName>CBailey</EName> <ID>22222</ID> </Employee> <Employee> <EName>Meghan</EName> <ID>12345</ID> </Employee> </Employees> PLEASE NOTE:This XML file has 100 nodes. I just put 1 to indicate the structure.

    Read the article

  • how to read in a list of custom configuration objects

    - by Johnny
    hi, I want to implement Craig Andera's custom XML configuration handler in a slightly different scenario. What I want to be able to do is to read in a list of arbitrary length of custom objects defined as: public class TextFileInfo { public string Name { get; set; } public string TextFilePath { get; set; } public string XmlFilePath { get; set; } } I managed to replicate Craig's solution for one custom object but what if I want several? Craig's deserialization code is: public class XmlSerializerSectionHandler : IConfigurationSectionHandler { public object Create(object parent, object configContext, XmlNode section) { XPathNavigator nav = section.CreateNavigator(); string typename = (string)nav.Evaluate("string(@type)"); Type t = Type.GetType(typename); XmlSerializer ser = new XmlSerializer(t); return ser.Deserialize(new XmlNodeReader(section)); } } I think I could do this if I could get Type t = Type.GetType("System.Collections.Generic.List<TextFileInfo>") to work but it throws Could not load type 'System.Collections.Generic.List<Test1.TextFileInfo>' from assembly 'Test1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

    Read the article

  • deleting entire xml node with datagrid

    - by DuranL
    Hello, I have the following xml structure: <systemtest> <test id="0"> <name>Test One</name> </test> <test id="1"> <name>Test Two</name> </test> </systemtest> The name gets displayed in the 1ste colum of the datagrid, where in the 2nd colum there is a buttoncolumn with delete button. How exactly can i use xpath and navigate to the current node lets say with test id="0" and delete it (including name)? Its unclear how i can say to this method what row he has to delete exactly. XmlDocument XMLDoc = new XmlDocument(); XMLDoc.Load(XMLFile); XPathNavigator nav = XMLDoc.CreateNavigator(); nav.SelectSingleNode("...."); //?? nav.DeleteSelf(); //will this do the trick? Also the id gets generated in a seperate class where the above method should be. Thanks in advance.

    Read the article

  • Using ms: xpath functions inside XPathExpression

    - by Filini
    I am trying to use Microsoft XPath Extension Functions (such as ms:string-compare http://msdn.microsoft.com/en-us/library/ms256114.aspx) inside an XPathExpression object. These functions are extensions inside the MSXML library, and if I use them in an XslCompiledTransform (simply adding the "ms" namespace) they work like a charm: var xsl = @" <?xml version=""1.0"" encoding=""UTF-8""?> <xsl:stylesheet version=""2.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:fn=""http://www.w3.org/2005/xpath-functions"" xmlns:ms=""urn:schemas-microsoft-com:xslt""> <xsl:output method=""xml"" version=""1.0"" encoding=""UTF-8"" indent=""yes""/> <xsl:template match=""/Data""> <xsl:element name=""Result""> <xsl:value-of select=""ms:string-compare(@timeout1, @timeout2)""/> </xsl:element> </xsl:template> </xsl:stylesheet>"; var xslDocument = new XmlDocument(); xslDocument.LoadXml(xsl); var transform = new XslCompiledTransform(); transform.Load(xslDocument); Then I tried using them in an XPathExpression: XPathNavigator nav = document.DocumentElement.CreateNavigator(); XPathExpression expr = nav.Compile("ms:string-compare(/Data/@timeout1, /Data/@timeout2)"); XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable); manager.AddNamespace("ms", "urn:schemas-microsoft-com:xslt"); expr.SetContext(manager); nav.Evaluate(expr); But I get an exception "XsltContext is needed for this query because of an unknown function". XsltContext is a specific XmlNamespaceManager, but I don't know if it's possible to instantiate it without an actual XslCompiledTransform (it's abstract) and use it as my expression context. Is there any way to do this (or any other way to use ms: extensions inside an XPathExpression)?

    Read the article

  • Deleting items from datagrid (xml)

    - by Tonz
    Hello, I have a datagrid buttoncolumn which acts as delete buttons for my xml nodes. The elements are simply displayed in a boundcolumn, so there names get displayed. Each item generated gets a unique id (each time one is made id+++). My question his how can i remove a item (the entire element node with that certain id) when i click on one of the buttons in the bound column? <root> <element id="0"> <name>One</name> </element> <element id="1"> <name>Two</name> </element> </root> protected void dg_DeleteCommand(object sender, DataGridCommandEventArgs e) { XmlFunctions.Remove(index); }/*dg_DeleteCommand*/ (function on other class, where all my xml methods are written) public static void Remove(string index) { XmlDocument XMLDoc = new XmlDocument(); XMLDoc.Load(XMLFile); XPathNavigator nav = XMLDoc.CreateNavigator(); var node = nav.SelectSingleNode("/test/one[@id='" +???+ "']"); node.DeleteSelf(); XMLDoc.Save(XMLFile); } Edit: added datagrid <asp:View ID="viewDelete" runat="server"> <asp:DataGrid ID="dgDelete runat="server" AutoGenerateColumns="False" OnDeleteCommand="dg_DeleteCommand"> <Columns> <asp:BoundColumn DataField="name" HeaderText="names" /> <asp:ButtonColumn ButtonType="PushButton" Text="Delete" CommandName="Delete" ></asp:ButtonColumn> </Columns> </asp:DataGrid> </asp:View>

    Read the article

  • c# Truncate HTML safely for article summary

    - by WickedW
    Hi All, Does anyone have a c# variation of this? This is so I can take some html and display it without breaking as a summary lead in to an article? http://stackoverflow.com/questions/1193500/php-truncate-html-ignoring-tags Save me from reinventing the wheel! Thank you very much ---------- edit ------------------ Sorry, new here, and your right, should have phrased the question better, heres a bit more info I wish to take a html string and truncate it to a set number of words (or even char length) so I can then show the start of it as a summary (which then leads to the main article). I wish to preserve the html so I can show the links etc in preview. The main issue I have to solve is the fact that we may well end up with unclosed html tags if we truncate in the middle of 1 or more tags! The idea I have for solution is to a) truncate the html to N words (words better but chars ok) first (be sure not to stop in the middle of a tag and truncate a require attribute) b) work through the opened html tags in this truncated string (maybe stick them on stack as I go?) c) then work through the closing tags and ensure they match the ones on stack as I pop them off? d) if any open tags left on stack after this, then write them to end of truncated string and html should be good to go!!!! -- edit 12112009 Here is what I have bumbled together so far as a unittest file in VS2008, this 'may' help someone in future My hack attempts based on Jan code are at top for char version + word version (DISCLAIMER: this is dirty rough code!! on my part) I assume working with 'well-formed' HTML in all cases (but not necessarily a full document with a root node as per XML version) Abels XML version is at bottom, but not yet got round to fully getting tests to run on this yet (plus need to understand the code) ... I will update when I get chance to refine having trouble with posting code? is there no upload facility on stack? Thanks for all comments :) using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Xml; using System.Xml.XPath; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace PINET40TestProject { [TestClass] public class UtilityUnitTest { public static string TruncateHTMLSafeishChar(string text, int charCount) { bool inTag = false; int cntr = 0; int cntrContent = 0; // loop through html, counting only viewable content foreach (Char c in text) { if (cntrContent == charCount) break; cntr++; if (c == '<') { inTag = true; continue; } if (c == '>') { inTag = false; continue; } if (!inTag) cntrContent++; } string substr = text.Substring(0, cntr); //search for nonclosed tags MatchCollection openedTags = new Regex("<[^/](.|\n)*?>").Matches(substr); MatchCollection closedTags = new Regex("<[/](.|\n)*?>").Matches(substr); // create stack Stack<string> opentagsStack = new Stack<string>(); Stack<string> closedtagsStack = new Stack<string>(); // to be honest, this seemed like a good idea then I got lost along the way // so logic is probably hanging by a thread!! foreach (Match tag in openedTags) { string openedtag = tag.Value.Substring(1, tag.Value.Length - 2); // strip any attributes, sure we can use regex for this! if (openedtag.IndexOf(" ") >= 0) { openedtag = openedtag.Substring(0, openedtag.IndexOf(" ")); } // ignore brs as self-closed if (openedtag.Trim() != "br") { opentagsStack.Push(openedtag); } } foreach (Match tag in closedTags) { string closedtag = tag.Value.Substring(2, tag.Value.Length - 3); closedtagsStack.Push(closedtag); } if (closedtagsStack.Count < opentagsStack.Count) { while (opentagsStack.Count > 0) { string tagstr = opentagsStack.Pop(); if (closedtagsStack.Count == 0 || tagstr != closedtagsStack.Peek()) { substr += "</" + tagstr + ">"; } else { closedtagsStack.Pop(); } } } return substr; } public static string TruncateHTMLSafeishWord(string text, int wordCount) { bool inTag = false; int cntr = 0; int cntrWords = 0; Char lastc = ' '; // loop through html, counting only viewable content foreach (Char c in text) { if (cntrWords == wordCount) break; cntr++; if (c == '<') { inTag = true; continue; } if (c == '>') { inTag = false; continue; } if (!inTag) { // do not count double spaces, and a space not in a tag counts as a word if (c == 32 && lastc != 32) cntrWords++; } } string substr = text.Substring(0, cntr) + " ..."; //search for nonclosed tags MatchCollection openedTags = new Regex("<[^/](.|\n)*?>").Matches(substr); MatchCollection closedTags = new Regex("<[/](.|\n)*?>").Matches(substr); // create stack Stack<string> opentagsStack = new Stack<string>(); Stack<string> closedtagsStack = new Stack<string>(); foreach (Match tag in openedTags) { string openedtag = tag.Value.Substring(1, tag.Value.Length - 2); // strip any attributes, sure we can use regex for this! if (openedtag.IndexOf(" ") >= 0) { openedtag = openedtag.Substring(0, openedtag.IndexOf(" ")); } // ignore brs as self-closed if (openedtag.Trim() != "br") { opentagsStack.Push(openedtag); } } foreach (Match tag in closedTags) { string closedtag = tag.Value.Substring(2, tag.Value.Length - 3); closedtagsStack.Push(closedtag); } if (closedtagsStack.Count < opentagsStack.Count) { while (opentagsStack.Count > 0) { string tagstr = opentagsStack.Pop(); if (closedtagsStack.Count == 0 || tagstr != closedtagsStack.Peek()) { substr += "</" + tagstr + ">"; } else { closedtagsStack.Pop(); } } } return substr; } public static string TruncateHTMLSafeishCharXML(string text, int charCount) { // your data, probably comes from somewhere, or as params to a methodint XmlDocument xml = new XmlDocument(); xml.LoadXml(text); // create a navigator, this is our primary tool XPathNavigator navigator = xml.CreateNavigator(); XPathNavigator breakPoint = null; // find the text node we need: while (navigator.MoveToFollowing(XPathNodeType.Text)) { string lastText = navigator.Value.Substring(0, Math.Min(charCount, navigator.Value.Length)); charCount -= navigator.Value.Length; if (charCount <= 0) { // truncate the last text. Here goes your "search word boundary" code: navigator.SetValue(lastText); breakPoint = navigator.Clone(); break; } } // first remove text nodes, because Microsoft unfortunately merges them without asking while (navigator.MoveToFollowing(XPathNodeType.Text)) { if (navigator.ComparePosition(breakPoint) == XmlNodeOrder.After) { navigator.DeleteSelf(); } } // moves to parent, then move the rest navigator.MoveTo(breakPoint); while (navigator.MoveToFollowing(XPathNodeType.Element)) { if (navigator.ComparePosition(breakPoint) == XmlNodeOrder.After) { navigator.DeleteSelf(); } } // moves to parent // then remove *all* empty nodes to clean up (not necessary): // TODO, add empty elements like <br />, <img /> as exclusion navigator.MoveToRoot(); while (navigator.MoveToFollowing(XPathNodeType.Element)) { while (!navigator.HasChildren && (navigator.Value ?? "").Trim() == "") { navigator.DeleteSelf(); } } // moves to parent navigator.MoveToRoot(); return navigator.InnerXml; } [TestMethod] public void TestTruncateHTMLSafeish() { // Case where we just make it to start of HREF (so effectively an empty link) // 'simple' nested none attributed tags Assert.AreEqual(@"<h1>1234</h1><b><i>56789</i>012</b>", TruncateHTMLSafeishChar( @"<h1>1234</h1><b><i>56789</i>012345</b>", 12)); // In middle of a! Assert.AreEqual(@"<h1>1234</h1><a href=""testurl""><b>567</b></a>", TruncateHTMLSafeishChar( @"<h1>1234</h1><a href=""testurl""><b>5678</b></a><i><strong>some italic nested in string</strong></i>", 7)); // more Assert.AreEqual(@"<div><b><i><strong>1</strong></i></b></div>", TruncateHTMLSafeishChar( @"<div><b><i><strong>12</strong></i></b></div>", 1)); // br Assert.AreEqual(@"<h1>1 3 5</h1><br />6", TruncateHTMLSafeishChar( @"<h1>1 3 5</h1><br />678<br />", 6)); } [TestMethod] public void TestTruncateHTMLSafeishWord() { // zero case Assert.AreEqual(@" ...", TruncateHTMLSafeishWord( @"", 5)); // 'simple' nested none attributed tags Assert.AreEqual(@"<h1>one two <br /></h1><b><i>three ...</i></b>", TruncateHTMLSafeishWord( @"<h1>one two <br /></h1><b><i>three </i>four</b>", 3), "we have added ' ...' to end of summary"); // In middle of a! Assert.AreEqual(@"<h1>one two three </h1><a href=""testurl""><b class=""mrclass"">four ...</b></a>", TruncateHTMLSafeishWord( @"<h1>one two three </h1><a href=""testurl""><b class=""mrclass"">four five </b></a><i><strong>some italic nested in string</strong></i>", 4)); // start of h1 Assert.AreEqual(@"<h1>one two three ...</h1>", TruncateHTMLSafeishWord( @"<h1>one two three </h1><a href=""testurl""><b>four five </b></a><i><strong>some italic nested in string</strong></i>", 3)); // more than words available Assert.AreEqual(@"<h1>one two three </h1><a href=""testurl""><b>four five </b></a><i><strong>some italic nested in string</strong></i> ...", TruncateHTMLSafeishWord( @"<h1>one two three </h1><a href=""testurl""><b>four five </b></a><i><strong>some italic nested in string</strong></i>", 99)); } [TestMethod] public void TestTruncateHTMLSafeishWordXML() { // zero case Assert.AreEqual(@" ...", TruncateHTMLSafeishWord( @"", 5)); // 'simple' nested none attributed tags string output = TruncateHTMLSafeishCharXML( @"<body><h1>one two </h1><b><i>three </i>four</b></body>", 13); Assert.AreEqual(@"<body>\r\n <h1>one two </h1>\r\n <b>\r\n <i>three</i>\r\n </b>\r\n</body>", output, "XML version, no ... yet and addeds '\r\n + spaces?' to format document"); // In middle of a! Assert.AreEqual(@"<h1>one two three </h1><a href=""testurl""><b class=""mrclass"">four ...</b></a>", TruncateHTMLSafeishCharXML( @"<body><h1>one two three </h1><a href=""testurl""><b class=""mrclass"">four five </b></a><i><strong>some italic nested in string</strong></i></body>", 4)); // start of h1 Assert.AreEqual(@"<h1>one two three ...</h1>", TruncateHTMLSafeishCharXML( @"<h1>one two three </h1><a href=""testurl""><b>four five </b></a><i><strong>some italic nested in string</strong></i>", 3)); // more than words available Assert.AreEqual(@"<h1>one two three </h1><a href=""testurl""><b>four five </b></a><i><strong>some italic nested in string</strong></i> ...", TruncateHTMLSafeishCharXML( @"<h1>one two three </h1><a href=""testurl""><b>four five </b></a><i><strong>some italic nested in string</strong></i>", 99)); } } }

    Read the article

1 2  | Next Page >