enter code herehey guys im having trouble with xelement when im trying to open the test page an unhandled exception appears and that because the tag doesn't match the closing in another line i tried to add the closings tag but the error happens before the adding function could work
test page http://densetsu.org/PP2012/benchmark1.html
so is there is a way to pass the tag problems without losing the tag effect
this is the main code:
XElement tree = XElement.Load(toolStripTextBox1.Text);
String s = tree.ToString();
textBox1.Text = String_dealer.addmissing(s);
this is the string changer
public static String addmissing(String txt)
{
if (txt.Contains("<br>") || (txt.Contains("</br>")))
{
txt.Replace("<br>", "<br></br>");
txt.Replace("</br>", "<br></br>");
}
else if (txt.Contains("<hr>") || (txt.Contains("</hr>")))
{
txt.Replace("<hr>", "<hr> </hr>");
txt.Replace("</hr>", "<hr> </hr>");
}
return txt;
}
and the problem text :
An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: The 'hr' start tag on line 8 does not match the end tag of 'br'. Line 9, position 10.
using a stream reader from a web request then storing the stream into an String file after that you can pass the string to sgml.reader which will transform the html into valid xml
Related
I am using XPathSelectElement to get some elements from an XML file. It works when those elements are present in the XML file. If the selected element is NOT in the XML it naturally throws a "Null Reference" exception. Which is fine. I would expect it to do that. However, I want to be able to catch that exception and do nothing if the XPathSelectElement is null.
Code that works as expected:
public void LoadBonusDescription()
{
string Race = CharRaceSelector.Text;
string bonus = RequirementsBox.Text;
XDocument doc = XDocument.Load($"{Gamepath}");
string description = (string)doc.XPathSelectElement($"//RaceID[#id='{Race}']/Bonus[#id='{bonus}']/Description").Value;
//DescriptionBox is a listBox
DescriptionBox.Text = description;
}
I tried throwing in an if statement like:
if (description == null)
{
return;
}
else
{
DescriptionBox.Text = description;
}
But it doesn't hit that part, and throws the exception at the string variable assignment here:
string description = (string)doc.XPathSelectElement($"//RaceID[#id='{Race}']/Bonus[#id='{bonus}']/Description").Value;
How do I catch the exception BEFORE (or during) the variable assignment in order to run the if statement?
If I can't catch it, is there a way to disable the DescriptionBox listBox AND NOT turn the text in the box to gray (as it does with DescriptionBox.Enabled = false;)?
Basically I want to prevent users from selecting items that aren't available in the XML file.
Added:
var description = (string)doc.XPathSelectElement($"//RaceID[#id='{Race}']/Bonus[#id='{bonus}']/Description");
if (description == null)
{
return;
}
else
{
DescriptionBox.Text = description;
}
as #dbc suggested and it works perfectly!
I'm having trouble with datascraping on this web address: http://patorjk.com/software/taag/#p=display&f=Graffiti&t=Type%20Something%20.
The problem is: I've written a code that is supposed to grab the contents of a certain node and display it on console. However, the contents withing the node and the specific node itself seem to be unreachable, but I know they exists for the fact that I've created a condition within my code in order to let me know if nodes withing a certain body are being found and it is indeed being found but not displayed for some reason:
private static void getTextArt(string font, string word)
{
HtmlWeb web = new HtmlWeb();
//cureHtml method is just meant to return the http address
HtmlDocument htmlDoc = web.Load(cureHtml(font, word));
if(web.Load(cureHtml(font, word)) != null)
Console.WriteLine("Connection Established");
else
Console.WriteLine("Connection Failed!");
var nodes = htmlDoc.DocumentNode.SelectSingleNode(nodeXpath).ChildNodes;
foreach(HtmlNode node in nodes)
{
if(node != null)
Console.WriteLine("Node Found.");
else
Console.WriteLine("Node not found!");
Console.WriteLine(node.OuterHtml);
}
}
private const string nodeXpath = "//div[#id='maincontent']";
}
The Html displayed by the website looks like this:
The Html code within the website. Arrows point at the node I'm trying to reach and the content within it I'm trying to display on the console
When I run my code on console to check for the node and its contents and try to display the OuterHtml string of the Xpath, this is how console will display it to me:
Console Window Display
I hope some of you are able to explain to me why is it behaving this way. I've tried all kinds of searches on google for two days trying to figure out the problem for no use. Thank you all in advance.
The content you desire is loaded dynamically.
Use the HtmlWeb.LoadFromBrowser() method instead. Also, check htmlDoc for null, instead of calling it twice. Your current logic doesn't guarantee your state.
HtmlDocument htmlDoc = web.LoadFromBrowser(cureHtml(font, word));
if (htmlDoc != null)
Console.WriteLine("Connection Established");
else
Console.WriteLine("Connection Failed!");
Also, you'll need to decode the result.
Console.WriteLine(WebUtility.HtmlDecode(node.OuterHtml));
If this doesn't work, then your cureHtml() method is broken, or you're targeting .NET Core :)
I am trying to get an information from the web (adress in my code) with HtmlAgilityPack in C#, but I have to wait until the <div class="center fs22 green lh32"> is loaded on the page.
var url = $"https://www.webpage.com/test{info}";
var web = new HtmlWeb();
var doc = web.LoadFromBrowser(url, html =>
{
return !html.Contains("<div class=\"center fs22 green lh32\"></div>");
});
string adress = doc.DocumentNode
.SelectSingleNode("//td/span[#id='testedAddress")
.Attributes["value"].Value;
Unfortunally I always get this error when I start my code :
Translation : 'Unclosed chain.'
How can I pass this error ?
The error occurs on the following line:
.SelectSingleNode("//td/span[#id='testedAddress")
There is a ' and a ] missing at the end of that XPath expression. That inner part incompletely enclosed in ' is the "chain" (actually, a string in English, or "chaîne de caractères" in French) the error message is talking about.
So, the line should read instead:
.SelectSingleNode("//td/span[#id='testedAddress']")
I get a error with Newtonjson when parsing my data from Facebook ajax.
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
Additional information: Unterminated string. Expected delimiter: ". Path 'payload.entries[364].text', line 1, position 277614.
Please send me a solution to solve that error .
I put your json in a console application to see if it loads.
I was able to parse it fine using this code:
static void Main(string[] args)
{
Assembly asm = Assembly.GetAssembly(typeof(Program));
using (var stream = asm.GetManifestResourceStream("ConsoleApplication1.json.json"))
{
TextReader tr = new StreamReader(stream);
var json = tr.ReadToEnd();
var thing = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
}
}
Note: ConsoleApplication1.json.json above is an embeded resource called "json.json" in which I put the json you linked in.
I suspect you are doing something in your code somewhere with the json that is making it invalid.
I've come across a SharePoint problem that I hope someone can help with. Basically, when I am trying to add a column called "MigratedChemist" to a list called "WorkCards" (pListName in the method parameters). No matter what I try I am getting a FaultException error raised when calling UpdateList. I am connecting using the SharePoint web service. I have confirmed the following:
The column doesn't already exist and I do have permissions to create it in SharePoint
The connection to SharePoint is established corectly to /_vti_bin/lists.asmx
The list name is correct as I have another method which returns items from the list and that works perfectly.
The xVersion and xId values are set correctly when the program runs and passed as parameters - as far as I am concerned I should just be able to pass the list name, as opposed to the GUID, but neither method works.
My code is as follows:
public static bool AddColumnToList(string pUri, string pListName, string pViewName, string pMaxRecords)
{
string version = string.Empty;
XAttribute xId = null;
XAttribute xVersion = null;
try
{
XElement listDetails = client.GetList(pListName);
xVersion = listDetails.Attribute("Version");
xId = listDetails.Attribute("ID");
}
catch { throw; }
XElement ndNewFields = new XElement ("Fields", "");
string newXml = "<Method ID='1' Cmd='New'><Field Name='MigratedChemist' Type='Text' DisplayName='MigratedChemist' /></Method></Fields>";
ndNewFields.Add(newXml);
XElement result;
try
{
result = client.UpdateList(xId.Value, null, ndNewFields, null, null, xVersion.Value);
}
catch (FaultException fe)
{
}
return true;
}
In addition to this does anyone know how to get any decent information from FaultRequest? At the moment I get the following error message, which is of no use and there appears to be no extra detail. I have tried, as some have suggested removing the error handling and letting the program halt, but that doesn't give me any extra information either.
{"Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown."}
For future reference I have solved both the problem of the SharePoint update failing AND the FaultException problem, so am including it here for posterity:
Problem 1 - Problem with UpdateList
This problem was caused because my XML was malformed. When I called ndNewFields.Add(newXml) then XML that was being returned was replacing < and > than with control characters, as shown below (I have added an extra space because this editor converts them automatically.
<Method ID="1" Cmd="New"> ;< ;Field Name="MigratedChemist"> ;< ;/Field> ;< ;/Method> ;
Now, I did notice this pretty early on but wasn't sure whether it would cause a problem or not. However using the XElement.Parse command I was able to remove these characters and this resolved the problem:
ndNewFields.Add(XElement.Parse (newXml));
Problem 2 - Problem with the SharePoint error coming back as FaultException
This has been bugging for me ages so I am glad I have finally solved it. I can't take credit for it, as I took it from another page, but the following code was how I got the details.
catch (FaultException fe)
{
MessageFault msgFault = fe.CreateMessageFault();
XmlElement elm = msgFault.GetDetail<XmlElement>();
}
Hopefully this will save someone some frustration in the future!
Andrew