<Peoples>
<People>
<Name>RadheyJang</Name>
<Location>India</Location>
<Work>Software Developer</Work>
<Point>5</Point>
<details>
<People>
<Name>ArunaTiwari</Name>
<Location>India</Location>
<Work>SoFtwareCoder</Work>
<Point>3</Point>
<details/>
<Test>A</Test>
</People>
</details>
<Test>NA</Test>
</People>
</Peoples>
I am able to Read That Xml By using below code .
XDocument xmlDoc = XDocument.Load(str);
var vrresult = from a in xmlDoc.Descendants("People")
select new
{
Name= a.Element("Name").Value,
Location= a.Element("Location").Value,
Point= a.Element("Point").Value
};
GridView1.DataSource = vrresult;
GridView1.DataBind();
But It is reading the Contents of details also . I want to Skip reading the Content inside the details Element . Please let me know how can i skip the Content Inside the details .
You need to use XPath for this...
using System.Xml.XPath;
string xml = #"
<Peoples>
<People>
<Name>RadheyJang</Name>
<Location>India</Location>
<Work>Software Developer</Work>
<Point>5</Point>
<details>
<People>
<Name>ArunaTiwari</Name>
<Location>India</Location>
<Work>SoFtwareCoder</Work>
<Point>3</Point>
<details/>
<Test>A</Test>
</People>
</details>
<Test>NA</Test>
</People>
</Peoples>";
XDocument xmlDoc = XDocument.Parse(xml);
var vrresult = from a in xmlDoc.XPathSelectElements("/Peoples/People")
select new
{
Name = a.Element("Name").Value,
Location = a.Element("Location").Value,
Point = a.Element("Point").Value
};
var ele = XElement.Parse(xml);
// change to XElement.Load if loading from file
var result = ele.Descendants("Section").Zip(ele.Descendannt("Mark"), (s,m) => new {Section = s.Value, Mark = m.Value}); Now you can create your DataTable:
var table = new DataTable();
var marks = new DataColumn("Mark");
var sections = new DataColumn("Sections");
table.Columns.Add(marks); table.Columns.Add(sections);
foreach (var item in result)
{
var row = table.NewRow();
row["Mark"] = item.Mark;
row["Sections"] = item.Section;
table.Rows.Add(row);
}
Try this Code ..
The only thing I can think of is that the XML is not legal:
<Peoples>
<People> *You have an opening People tag here*
<Name>RadheyJang</Name>
<Location>India</Location>
<Work>Software Developer</Work>
<Point>5</Point>
<details> *You create a details tag here*
<People> *You generate the same tag inside of another People tag*
<Name>ArunaTiwari</Name>
<Location>India</Location>
<Work>SoFtwareCoder</Work>
<Point>3</Point>
<details/> *Then you close the details tag here*
<Test>A</Test>
</People>
</details> *Then you close another one, but there is not a second opening detail tag*
<Test>NA</Test>
</People>
</Peoples>
I'm not sure if this helps at all, but you might want to consider fixing up your XML.
Related
Please help. How to read from xml sub tree. I have xml doc:
<data>
<Infos>
<Info>
<AddressFk>1</AddressFk>
<AddressLine1>1970</AddressLine1>
<AddressLine2>Napa Ct.</AddressLine2>
<Phone>
<dataAsString1>111111</string>
<dataAsString2>222222</string>
<dataAsString3>333333</string>
</Phone>
<City>Bothell</City>
</Info>
</Infos>
I read xml using XDocument:
XDocument xdoc = XDocument.Load("1.xml");
foreach (XElement addresList in xdoc.Document.Element("data").Elements("Infos").Elements("Info"))
{
address = new Address();
address.id = (string)addresList.Element("AddressFk");
address.Line1 = (string)addresList.Element("AddressLine1");
address.Line2 = (string)addresList.Element("AddressLine2");
address.City = (string)addresList.Element("City");
}
how to get the structure <Phone> ???
Use Elements
var phones = addresList.Element("Phone").Elements("string");
foreach(var phone in phones)
{
Console.WriteLine((string)phone);
}
for the future, it is bad practice to use tag names with reserved words
I have the following XML structure:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<values>
<bool key="Chapter_1.Boolean1.value">true</bool>
<string key="Chapter_1.Text1.value">abc</string>
<string key="Chapter_1.Text2.value">Inspection done (2)</string>
<number key="Chapter_1.Number1.value">128</number>
<number key="Chapter_1.Number2.value">34539718</number>
<number key="Chapter_1.Number3.value">3</number>
<datetime key="Chapter_2.Chapter_2_1.DateTime1.value">2020-06-02T09:00:00+03:00</datetime>
<datetime key="Chapter_2.Chapter_2_1.DateTime2.value">2016-02-05T00:00:00+02:00</datetime>
<string key="Chapter_3.Text4.value">52</string>
<string key="Chapter_3.Text5.value">22</string>
<number key="Chapter_3.Number6.value">34539718</number>
</values>
and the following C# code:
var settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Auto;
settings.IgnoreWhitespace = true;
settings.IgnoreComments = true;
using (var xmlReader = new XmlTextReader(xmlFilePath))
{
while (xmlReader.Read())
{
var nodeName = xmlReader.Name;
var attrName = xmlReader.GetAttribute("key");
}
}
The problem is that the node name is empty and there are no attributes for the following keys:
Chapter_1.Text1.value
Chapter_1.Number1.value
Chapter_3.Text5.value
Anyone has any idea what could be the problem?
The code worked well here, I was able to access all xml tags and attributes.
Maybe you're confused because at each xmlReader.Read() it reads only one part of the tag. So to read all the tag with key "Chapter_1.Text1.value", first it reads a tag with name string and key "Chapter_1.Text1.value", then it reads something without a name, without a attribute, but with value "abc" and then it reads the tag closing with name string, but no attribute and no value.
It would be easier to use Xml to Linq :
var xml = XDocument.Load(__PATH_TO_XML__);
var values = xml.XPathSelectElements("/values/*")
.Select(x => new
{
Type = x.Name,
Key = x.Attribute("key"),
Value = x.Value
});
If you want to read the value as well, try this
using (var xmlReader = new XmlTextReader(#"yourxmlfile"))
{
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
var nodeName = xmlReader.Name;
var attrName = xmlReader.GetAttribute("key");
Console.WriteLine(nodeName);
Console.WriteLine(attrName);
}
if (xmlReader.NodeType==XmlNodeType.Text)
{
Console.WriteLine(xmlReader.Value);
}
}
}
I have an XML:
<?xml version="1.0" encoding="UTF-8"?>
<ticket>
<comments type="array">
<comment>
<attachments type="array">
<attachment>
<url>I NEED WHATEVER IS IN HERE</url>
</attachment>
</attachments>
</comment>
<comment>
<attachments type="array">
<attachment>
<url>I NEED WHATEVER IS IN HERE</url>
</attachment>
</attachments>
<comment>
</comments>
</ticket>
How would I go about getting whatever is inside the URL tag and add it to a <List>? I'm using C#.
Use:
var result = XDocument.Parse(inputXml)
.DescendantNodes().OfType<XText>().Select(e => e.Value).ToList();
Or using XPath:
var result = ((IEnumerable)XDocument.Parse(input).XPathEvaluate("//text()"))
.Cast<XText>().ToList();
To retrieve text only from url element use:
var result = XDocument.Parse(inputXml)
.Descendants("url").Select(e => e.Value).ToList();
or change above XPath: //url/text()
using (StringReader sr = new StringReader(xml_content))
{
XDocument xdoc = XDocument.Load(sr);
IList<string> values = xdoc.XPathSelectElements("ticket/comments/attachments/url").Select(e => e.Value).ToList();
}
Or, based on your use case in your comment:
var doc = new XmlDocument();
doc.LoadXml(xml_content);
IList<string> values = doc.SelectNodes("ticket/comments/attachments/url")
.Cast<XmlElement>().Select(e => e.InnerText).ToList();
Or you can use var values = xdoc.SelectSingleNode("ticket/comments/attachments/url").InnerXml;
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE Report SYSTEM "https://abc.mycompany.com/abc/processingreports/processeddtd/abcd_1_8.dtd">
<Report Name="Daily TRANSACTIONS"
Version="1.8"
xmlns="https://abc.mycompany.com/abc/processingreports/processeddtd/abcd_1_8.dtd"
OrgID="ABC_PQR" StartDate="2011-03-10T00:00:00+00:00" EndDate="2011-03-11T00:00:00+00:00">
<Requests>
<Request ID="2"
Date="2011-03-10T00:21:14+00:00"
OrderNumber="1">
<BillTo>
<FirstName />
</BillTo>
<LineItems>
<LineItem Number="0">
<Quantity />
</LineItem>
</LineItems>
</Request>
<Request ID="2"
Date="2011-03-10T00:21:14+00:00"
OrderNumber="1">
TransactionNumber="389958330911111">
<BillTo>
<FirstName>A</FirstName>
</BillTo>
<LineItems>
<LineItem Number="0">
<Quantity>1</Quantity>
</LineItem>
</LineItems>
<UniqueData>
<UniqueNumber>11111111111111111111111111111</UniqueNumber>
</UniqueData></Request></Requests></Report>
In above XML file using Linq i just
want to extract OrderNumber and
UniqueNumber
OrderNumber="1"
11111111111111111111111111111
Any ideas, suggestions to extract these details?
I can select elements from above xml file but UniqueNumber is not associated with OrderNumber
I am looking for something below (ignore lines where UniqueNumber is not present)
OrderNumber - assosicated UniqueNumber
Update
In "requiredElements" i am expecting two coulmns OrderNumber and UniqueNumber and holding associated values with each other as 1 and 11111 and so one
#region FileOpen with UTF8 Encoding
TextReader sr = new StreamReader(cFileName, Encoding.UTF8);
XDocument reportfile = XDocument.Load(sr, LoadOptions.SetBaseUri);
XElement xd = XElement.Parse(reportfile.ToString());
sr.Close();
#endregion
XNamespace ns = xd.Attribute("xmlns").Value;
var requiredElements = (from resultquery in reportfile.Descendants()
select new
{
OrderNumber = resultquery.Attribute("OrderNumber"),
UniqueNumber= (string)resultquery.Element(AddNameSpace(ns, "UniqueNumber")),
}
);
Here is some sample:
XDocument doc = XDocument.Load(#"file.xml");
XNamespace df = doc.Root.Name.Namespace;
var results = from request in doc.Descendants(df + "Request")
where request.Elements(df + "UniqueData").Elements(df + "UniqueNumber").Any()
select new
{
ordNumber = (int)request.Attribute("OrderNumber"),
uniqueNumber = (decimal)request.Element(df + "UniqueData").Element(df + "UniqueNumber")
};
foreach (var result in results)
{
Console.WriteLine("{0}-{1}", result.ordNumber, result.uniqueNumber);
}
I need to get the number next to the word text, in this case the number is 1
<SD>
<POPULARITY URL="google.com/" TEXT="1"/>
<REACH RANK="1"/>
<RANK DELTA="+0"/>
</SD>
How can I get the number in c#
Thanks
In addition to the examples above you could try using linq to xml
See below.
var str = #"<ALEXA VER='0.9' URL='google.com/' HOME='0' AID='='>
<SD TITLE='A' FLAGS='DMOZ' HOST='google.com'>
<TITLE TEXT='Google '/>
<ADDR STREET='' CITY='' STATE='' ZIP='' COUNTRY='' />
<CREATED DATE='15-Sep-1997' DAY='15' MONTH='09' YEAR='1997'/>
<PHONE NUMBER='unlisted'/>
<OWNER NAME='unlisted'/>
<EMAIL ADDR='dns-admin#google.com'/>
<LANG LEX='en'/>
<LINKSIN NUM='704402'/>
<SPEED TEXT='1581' PCT='48'/>
<REVIEWS AVG='4.5' NUM='524'/>
<CHILD SRATING='0'/>
<ASSOCS>
<ASSOC ID='googlecom'/></ASSOCS>
</SD>
<KEYWORDS>
<KEYWORD VAL='Mountain View'/>
</KEYWORDS><DMOZ>
<SITE BASE='google.com/' TITLE='Google' DESC='Enables users to search the Web, Usenet, and images. Features include PageRank, caching and translation of results, and an option to find similar pages. The companys focus is developing search technology.'>
<CATS>
<CAT ID='Top/Computers/Internet/Searching/Search_Engines/Google' TITLE='Search Engines/Google' CID='374822'/>
<CAT ID='Top/Regional/North_America/United_States/California/Localities/M/Mountain_View/Business_and_Economy/Industrial/Computers_and_Internet' TITLE='Industrial/Computers and Internet' CID='625367'/>
<CAT ID='Top/World/Arabic/إقليمـي/الشرق_الأوسط/السعودية/تجارة_و_أقتصاد/كمبيوتر_و_إنترنت/محركات_بحث' TITLE='كمبيوتر و إنترنت/محركات بحث' CID='204954'/>
<CAT ID='Top/World/Français/Informatique/Internet/Recherche/Moteurs_de_recherche/Google' TITLE='Moteurs de recherche/Google' CID='247347'/>
</CATS>
</SITE>
</DMOZ>
<SD>
<POPULARITY URL='google.com/' TEXT='1'/>
<REACH RANK='1'/>
<RANK DELTA='+0'/>
</SD>
</ALEXA>";
var item = XElement.Parse(str);
var subSet = item.Elements("SD");
var actualItem = subSet.Where(x => x.Element("POPULARITY") != null).First();
var value = actualItem.Element("POPULARITY").Attribute("TEXT").Value;
Hope this helps
Something like this:
XmlDocument doc = new XmlDocument();
doc.LoadXml( #"<SD> <POPULARITY URL=""google.com/"" TEXT=""1""/> <REACH RANK=""1""/> <RANK DELTA=""+0""/> </SD> ");
XmlNode root = doc.FirstChild;
Debug.WriteLine(root["POPULARITY"].Attributes["TEXT"].InnerXml);
You can try:
XmlDocument doc = new Xmldocument();
doc.Load(stringWithYourXml);
XmlNode node = doc.SelectSingleNode("/SD/POPULARITY");
var val = node.Attributes["TEXT"].Value
Please consider this as a sample ( do some more checks and error detection )