I have this text in a rich text box named richTextBox:
<notification_counts>
<unseen>0</unseen>
</notification_counts>
<friend_requests_counts>
<unread>1</unread>
<unseen>**0**</unseen>
</friend_requests_counts>
I would like to extract the value from the unseen tag (0 in this example) and place it in the text box named textbox1. How should I go about doing this?
Full code
<?xml version="1.0" encoding="UTF-8"?>
<notifications_get_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd">
<messages>
<unread>0</unread>
<unseen>0</unseen>
<most_recent>****</most_recent>
</messages>
<pokes>
<unread>0</unread>
<most_recent>0</most_recent>
</pokes>
<shares>
<unread>0</unread>
<most_recent>0</most_recent>
</shares>
<notification_counts>
<unseen>0</unseen>
</notification_counts>
<friend_requests_counts>
<unread>1</unread>
<unseen>0</unseen>
</friend_requests_counts>
<friend_requests list="true">
<uid>***</uid>
</friend_requests>
<group_invites list="true"/>
<event_invites list="true"/>
</notifications_get_response>
If your rich text box only contains XML markup, you can parse it to extract the value you're interested in. For instance, using LINQ to XML:
using System.Xml.Linq;
textBox1.Text = XElement.Parse(richTextBox.Text)
.Descendant("friend_requests_counts")
.Element("unseen").Value;
EDIT: Since your XML markup contains namespaces, you have to take them into account when selecting the elements:
XNamespace fb = "http://api.facebook.com/1.0/";
textBox1.Text = XDocument.Parse(richTextBox.Text).Root
.Element(fb + "friend_requests_counts")
.Element(fb + "unseen").Value;
Related
I have a task where i need to create a conversion program from OmniPage XML ocr output into ALTO XML.
The output of OmniPage XML is really different from ALTO XML.
I tried to find an ALTO XML file and trying to figure out where those values came from.
I need to get the formula of SP Tag WIDTH.
Below is the sample XML i'm trying to figure out
<TextLine ID="P1_TL00002" HPOS="26.00" VPOS="98.00" WIDTH="1667.00" HEIGHT="130.00">
<String ID="P1_ST00002" HPOS="26.00" VPOS="106.00" WIDTH="387.00" HEIGHT="95.00" CONTENT="Twenties" WC="0.99" CC="06370005"/>
<SP ID="P1_SP00001" HPOS="413.00" VPOS="201.00" WIDTH="29.00"/>
<String ID="P1_ST00003" HPOS="442.00" VPOS="98.00" WIDTH="246.00" HEIGHT="103.00" CONTENT="Glrls" WC="0.78" CC="00045"/>
<SP ID="P1_SP00002" HPOS="688.00" VPOS="201.00" WIDTH="26.00"/>
<String ID="P1_ST00004" HPOS="714.00" VPOS="98.00" WIDTH="178.00" HEIGHT="103.00" CONTENT="ancl" WC="0.54" CC="5660"/>
<SP ID="P1_SP00003" HPOS="892.00" VPOS="201.00" WIDTH="39.00"/>
<String ID="P1_ST00005" HPOS="931.00" VPOS="98.00" WIDTH="368.00" HEIGHT="130.00" CONTENT="FUppER" WC="0.83" CC="090000"/>
<SP ID="P1_SP00004" HPOS="1299.00" VPOS="228.00" WIDTH="32.00"/>
<String ID="P1_ST00006" HPOS="1331.00" VPOS="98.00" WIDTH="362.00" HEIGHT="106.00" CONTENT="PAshiON" WC="0.76" CC="0008206"/>
</TextLine>
I already figured out the values of HPOS and VPOS.
I used c# Rect class
Rect r = new Rect(26, 106, 387, 95);
Debug.WriteLine("BottomRight: " + r.BottomRight);
BottomRight: 413,201
But I can't figure where the SP tag's WIDTH value comes from.
Please help me.
Looks like it’s just the difference between the SP tags HPOS and the following String tags HPOS, e.g. 413.00 + 29.00 = 442.00, 688.00 + 26.00 = 714.00, and so on.
Below is the sample xml,
<?xml version="1.0" encoding="utf-8"?>
<UsersList>
<User>
<Name>sam&Tim</Name>
<Address>21, bills street, CA</Address>
<Issues>"Issues1", "Issues2"</Issues>
</User>
</UsersList>
c#:
string xml = System.IO.File.ReadAllText(#"E:\Sample.xml");
xml = System.Text.RegularExpressions.Regex.Replace(xml, "<(?![_:a-z][-._:a-z0-9]*\b[^<>]*>)", "<");
XDocument doc = XDocument.Parse(xml);
i need to convert the special charecters (<,>,",',&) and i am using the above regex. but parse method throws an error. any help please how to resolve the issue
See your current code converts XML like this
<?xml version="1.0" encoding="utf-8"?>
<UsersList>
<User>
<Name>sam&Tim</Name>
<Address>21, bills street, CA</Address>
<Issues>"Issues1", "Issues2"</Issues>
</User>
</UsersList>
Whereas Parse is looking it like this
<?xml version="1.0" encoding="utf-8"?>
<UsersList>
<User>
<Name>sam and Tim</Name>
<Address>21, bills street, CA</Address>
<Issues>"Issues1", "Issues2"</Issues>
</User>
</UsersList>
and thus you should not be converting < to < but XML contains sam&Tim would not allow you to Parse it. thus you can use
xml = xml.Replace("&", " n ");//n or and or some other char or string you want
instead of
xml = System.Text.RegularExpressions.Regex.Replace(xml, "<(?![_:a-z][-._:a-z0-9]*\b[^<>]*>)", "<");
Hope this will help you to parse it.
You can give a try with:
string xml = System.IO.File.ReadAllText(#"E:\Sample.xml");
xml = ReplaceXMLEncodedCharacters(xml)
public string ReplaceXMLEncodedCharacters(string input)
{
const string pattern = #"&#(x?)([A-Fa-f0-9]+);";
MatchCollection matches = Regex.Matches(input, pattern);
int offset = 0;
foreach (Match match in matches)
{
int charCode = 0;
if (string.IsNullOrEmpty(match.Groups[1].Value))
charCode = int.Parse(match.Groups[2].Value);
else
charCode = int.Parse(match.Groups[2].Value, System.Globalization.NumberStyles.HexNumber);
char character = (char)charCode;
input = input.Remove(match.Index - offset, match.Length).Insert(match.Index - offset, character.ToString());
offset += match.Length - 1;
}
return input;
}
Your problem is that your original XML is not a valid XML document, because is contains an unescaped ampersand ('&') which is explicitly forbidden by the standard that says
The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
To make it valid, you must use & instead of a literal &. Trying to "correct" it is not practical and a totally bad idea in the general case, because you can never be sure, where in your XML & stands for a literal & and where it is part of an XML entity. If it were possible to distinguish these usages unambiguously, that rule could be embedded in XML parsers and we would not have to deal with it.
A valid, standard-conformant representation of your document would be
<?xml version="1.0" encoding="utf-8"?>
<UsersList>
<User>
<Name>sam&Tim</Name>
<Address>21, bills street, CA</Address>
<Issues>"Issues1", "Issues2"</Issues>
</User>
</UsersList>
I need to format my xml string to display it in RDLC report, arranged by tags. Something like
<Root>
<Child>
<SubChild>...</SubChild>
</Child>
</Root>
I can't seem to find a way to do that, other than just iterating through the string horribly and trying to arrange it manually. Is there a way to do it with some format function in RDLC or in some other way and pass it to RDLC already formatted?
You can use this function to format your XML strings outside RDLC.
You need to use XMLWriterSettings.OmitXmlDeclaration to save an indented XML without declaration line (i.e.: <?xml version="1.0" encoding="utf-16"?>)
Dim strXML As String = "<Root><Child><SubChild>test</SubChild></Child></Root>"
Dim xmlDoc As New System.Xml.XmlDocument
xmlDoc.LoadXml(strXML)
Dim xmlSettings As New System.Xml.XmlWriterSettings
xmlSettings.Indent = True
xmlSettings.OmitXmlDeclaration = True
Dim sb As New System.Text.StringBuilder
Using writer As System.Xml.XmlWriter = System.Xml.XmlWriter.Create(sb, xmlSettings)
xmlDoc.Save(writer)
End Using
MsgBox(sb.ToString())
I have a xml-document that simplified looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Node1 separator=" " />
There is a \t as attribute value.
When executing this code
var path = #"C:\test.xml";
var doc = XDocument.Load(path);
doc.Save(path);
the attribute value changed from tab to space.
<?xml version="1.0" encoding="utf-8"?>
<Node1 separator=" " />
Is there a way to preserve the origin value, because it is required to be a tab?
This is "XML whitespace normalization in attributes" portion of XML:Attribute-Value Normalization which is default behavior when handling XML documents.
For a white space character (#x20, #xD, #xA, #x9), append a space character (#x20) to the normalized value
You should be able to use XmlTextReader.Normalization property as described here. XmlDocument can load from reader XmlDocument.Load.
var path = #"C:\test.xml";
XmlDocument doc = new XmlDocument();
XmlTextReader reader = new XmlTextReader(path);
doc.Load(reader);
var s = doc.SelectSingleNode("*/#*").InnerText;
Console.WriteLine("|{0}|, {1}", (int)s[0], s.Length); // prints 9 - ASCII code of tab
doc.Save(path);
I have this xml file that i have created pragmatically using C# :-
<Years>
<Year Year="2011">
<Month Month="10">
<Day Day="10" AccessStartTime="01:15 PM" ExitTime="01:15 PM" />
<Day Day="11" AccessStartTime="01:15 PM" ExitTime="01:15 PM" />
<Day Day="12" AccessStartTime="01:15 PM" ExitTime="01:15 PM" />
<Day Day="13" AccessStartTime="01:15 PM" ExitTime="01:15 PM" />
</Month>
<Month Month="11">
<Day Day="12" AccessStartTime="01:16 PM" ExitTime="01:16 PM" />
</Month>
</Year>
</Years>
I am having problems when i want to get specfic data from it while i am using XmlReader or i am doing it the wrong way cause each time the reader reads one single line and i what i want is to get a list of all days in a specific month and a year
Use Linq-XML or post the code you have tried.
var list = from ele in XDocument.Load(#"c:\filename.xml").Descendants("Year")
select new
{
Year = (string)ele.Attribute("Year"),
Month= (string)ele.Element("Month").Attribute("Month"),
Day = (string)ele.Element("Month").Element("Day").Attribute("Day")
};
foreach (var t in list)
{
Console.WriteLine(t.Year + " " + t.Month + " " + t.Day );
}
I agree with AVD's suggestion of using LINQ to XML. Finding all the days for a specific year and month is simple:
XDocument doc = XDocument.Load("file.xml");
var days = doc.Elements("Year").Where(y => (int) y.Attribute("Year") == year)
.Elements("Month").Where(m => (int) m.Attribute("Month") == month)
.Elements("Day");
(This assumes that Month and Year attributes are specified on all Month and Year elements.)
The result is a sequence of the Day elements for the specified month and year.
In most cases I'd actually write one method call per line, but in this case I thought it looked better to have one full filter of both element and attribute per line.
Note that in LINQ, some queries end up being more readable using query expressions, and some are more readable in the "dot notation" I've used above.
You asked for an explanation of AVD's code, so you may be similarly perplexed by mine - rather than explain the bits of LINQ to XML and LINQ that my code happens to use, I strongly recommend that you read good tutorials on both LINQ and LINQ to XML. They're wonderful technologies which will help your code all over the place.
Take a look at this example how to represent the xml with root node and using xml reader how to get the data ....
using System;
using System.Xml;
class Program
{
static void Main()
{
// Create an XML reader for this file.
using (XmlReader reader = XmlReader.Create("perls.xml"))
{
while (reader.Read())
{
// Only detect start elements.
if (reader.IsStartElement())
{
// Get element name and switch on it.
switch (reader.Name)
{
case "perls":
// Detect this element.
Console.WriteLine("Start <perls> element.");
break;
case "article":
// Detect this article element.
Console.WriteLine("Start <article> element.");
// Search for the attribute name on this current node.
string attribute = reader["name"];
if (attribute != null)
{
Console.WriteLine(" Has attribute name: " + attribute);
}
// Next read will contain text.
if (reader.Read())
{
Console.WriteLine(" Text node: " + reader.Value.Trim());
}
break;
}
}
}
}
}
}
Input text [perls.xml]
<?xml version="1.0" encoding="utf-8" ?>
<perls>
<article name="backgroundworker">
Example text.
</article>
<article name="threadpool">
More text.
</article>
<article></article>
<article>Final text.</article>
</perls>
Output
Start <perls> element.
Start <article> element.
Has attribute name: backgroundworker
Text node: Example text.
Start <article> element.
Has attribute name: threadpool
Text node: More text.
Start <article> element.
Text node:
Start <article> element.
Text node: Final text.