I have the string which has the XML tag like
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<lab:lab xmlns:udf="http://ghjhjhj.com/ri/userdefined"
xmlns:ri="http://kjkj.com/ri"
xmlns:lab="http://iuiuu.com/ri/lab"
uri="https://hhjjhjhj.org/api/v2/labs/1">
<name>Administrative Lab</name>
<billing-address>
<street></street>
<city></city>
<state></state>
<country></country>
<postalCode></postalCode>
<institution></institution>
<department></department>
</billing-address>
<shipping-address>
<street></street>
<city></city>
<state></state>
<country></country>
<postalCode></postalCode>
<institution></institution>
<department></department>
</shipping-address>
<udf:field type="String" name="Account ID">adm</udf:field>
<website></website>
</lab:lab>"
In order to just extract the value adm i.e any value between the <udf> tag should I be using the XDocument or the XmlDocument.I understand I can use XDocument.Parse but this I am not sure how to give the tag name. I tried below
XDocument new_doc = XDocument.Parse(new_responseString);
var a = from udf in new_doc.Descendants("udf") select udf.Value;
But there can be additional udf fields in future so what will I be checking should be name="Account ID" and I am not sure how to do this
How can I retrieve this?
You can use Attribute method for retrieving attribute's value of XElement.
var udf = "http://ghjhjhj.com/ri/userdefined";
var new_doc = XDocument.Parse(new_responseString);
var fieldValues = doc.Descendants(udf + "field")
.Where(field => field.Attribute("name").Value.Equals("Account ID"))
.Select(field => field.Value);
foreach (var value in fieldValues)
{
Console.WriteLine(value);
}
If you need only one value then use FirstOrDefault method
var fieldValue =
doc.Descendants(udf + "field")
.FirstOrDefault(field => field.Attribute("name").Value.Equals("Account ID"))
.Value;
But be aware - this query will throw exception of there no elements with attribute name = "Account ID"
Probably this might do the trick for you
XNamespace laburi = "http://iuiuu.com/ri/lab";
XNamespace udfuri = "http://ghjhjhj.com/ri/userdefined";
XDocument xdoc = XDocument.Load("some.txt");
var a = xdoc.Elements(laburi + "lab").Elements(udfuri + "field").FirstOrDefault().Value;
Related
**I have an XML like this-
<?xml version="1.0" encoding="UTF-8"?>
<Tool_Parent>
<tool name="ABCD" id="226">
<category>Centralized</category>
<extension_id>0</extension_id>
<uses_ids>16824943 16824944</uses_ids>
</tool>
<tool name="EFGH" id="228">
<category>Automated</category>
<extension_id>0</extension_id>
<uses_ids>92440 16824</uses_ids>
</tool>
</Tool_Parent>
Based on the id of tool i want to print the uses_ids value,i.e if i search for 228 i should get 92440 16824.
I had tried like-
var toolData = (from toolElement in doc.Descendants("tool")
select new Tool_poco
{
a_Name = tool.Attribute("name").Value,
a_Id = tool.Attribute("id").Value,
e_ExtensionId = tool.Element("extension_id").Value,
e_UsesIds =tool.Element("uses_parm_ids").Value
});
where Tool_poco is a poco class for tool node containing declaration for member variable.
Now I want to get information related to a particular tool id in toolData variable.How to do it?
Note: I have variable like-
searched_Tool_id = Tool_Id_txtBx.Text.ToString();
Please let me know a way through which i can modify my above query for toolData.**
You can modify your query as
Tool_poco toolData = (from el in xelement.Elements("Employee")
where (string)el.Attribute("id") == "226"
select new Tool_poco
{
a_Name = el.Attribute("name").Value,
a_Id = el.Attribute("id").Value,
e_ExtensionId = el.Element("Name").Value,
e_UsesIds = el.Element("uses_ids").Value
}).FirstOrDefault();
You could start by doing something like this once you have an XDocument object loaded and ready:
var xdoc = XDocument.Parse(
#"<?xml version=""1.0"" encoding=""utf-8""?>
<Tool_Parent>
<tool name=""ABCD"" id=""226"">
<category>Centralized</category>
<extension_id>0</extension_id>
<uses_ids>16824943 16824944</uses_ids>
</tool>
<tool name=""EFGH"" id=""228"">
<category>Automated</category>
<extension_id>0</extension_id>
<uses_ids>92440 16824</uses_ids>
</tool>
</Tool_Parent>");
var root = xdoc.Root; // Got to have that root
if (root != null)
{
var id228query = (from toolElement in root.Elements("tool")
where toolElement.HasAttributes
where toolElement.Attribute("id").Value.Equals("228")
let xElement = toolElement.Element("uses_ids")
where xElement != null
select xElement.Value).FirstOrDefault();
Console.WriteLine(id228query);
Console.Read();
}
Output: 92440 16824
**Note: In reference to your example, one possible reason it was not working
for you could be that your xml references an element with name "uses_ids",
however, your query references an element with a similar, but not exact,
spelling with name "uses_parm_ids".**
<?xml version="1.0" encoding="UTF-8"?>
<meta>
<field type="xs-string" name="AssetId">TF00000002</field>
<field type="xs-string" name="Title">TitleOfAsset</field>
</meta>
I have this XML loaded in to a XDocument using the function
XDocument doc = XDocument.Parse(xmlData)
However, I want to be able to retrieve the text fields "TF00000002" and "TitleOfAsset" ... How do I go about doing this?
templateMetaData.assetID = doc
.Descendants()
.Where(p => p.Name.LocalName == "AssetId")
.ToString();
returns:
System.Linq.Enumerable+WhereEnumerableIterator`1[System.Xml.Linq.XElement]
Can anyone shine a light on this?
In your query, you are calling ToString on an IEnumerable<XElement> which will never give you the expected result, instead look for field elements under your Root and get their value:
var values = doc.Root
.Elements("field")
.Select(element => (string)element);
If you want to access your values using the name attribute you can use Dictionary:
var values = doc.Root
.Elements("field")
.ToDictionary(x => (string)x.Attribute("name"), x => (string)x);
Then you can access the value of AssetId:
var id = values["AssetId"];
I'm using XPathSelectElement to store data into an XML file. How can I in the code snippet below use a global variable name instead of id name 'City1'?
I want the code to be:
string myVariable = "City1"
XElement fname= country.XPathSelectElement("country/city/major[#id = myVariable]/firstname");
Thank you for your help
This is my XML:
<country>
<city>
<cityname>City1</cityname>
<citynr>111</citynr>
<person>
<name>Person1</name>
<name>Person2</name>
<name>Person3</name>
<name>Person4</name>
</person>
<major id=City1>
<firstname>Major1firstname</firstname>
<lastname>Major1lastname</lastname>
</major>
</city>
<city>
<cityname>City2</cityname>
<citynr>222</citynr>
<person>
<name>Person5</name>
<name>Person6</name>
<name>Person7</name>
<name>Person8</name>
</person>
<major id=City2>
<firstname>Major2firstname</firstname>
<lastname>Major2firstname</lastname>
</major>
</city>
</country>
Here is my code:
XDocument country= XDocument.Load(Server.MapPath("myXML.xml"));
XElement fname= country.XPathSelectElement("country/city/major[#id = 'City1']/firstname");
XElement lname= country.XPathSelectElement("country/city/major[#id = 'City1']/lastname");
fname.Value = firstname.Text;
lname.Value = lastname.Text;
country.Save(Server.MapPath("myXML.xml"));
I'd just use the selection methods within LINQ to XML instead:
XElement fname = country.Element("country")
.Elements("city")
.Elements("major")
.Where(x => (string) x.Attribute("id") == myVariable)
.Elements("firstname")
.FirstOrDefault();
(By using FirstOrDefault, the result will be null if no such element is found.)
You may use:
var fname = country
.XPathSelectElement(
"//country/city/major[#id = '" + myVariable + "']/firstname");
or
var fname = country
.XPathSelectElement(
String.Format("//country/city/major[#id = '{0}']/firstname", myVariable));
I believe that one way through which you might mitigate the XPath injection that #Tomalak mentions in the comment below is to use the XName type instead of string (exception handling left out of scope intently):
XName myVariable = "City1";
you are either looking for string.Format or the StringBuilder class.
fname= country.XPathSelectElement(string.Format("country/city/major[#id = '{0}']/firstname",myVariable));
references:
http://msdn.microsoft.com/de-de/library/fht0f5be(v=vs.85).aspx
http://msdn.microsoft.com/de-de/library/2839d5h5(v=vs.90).aspx
I am storing a xml in a string and using Xdocument i am parsing the string to xml from that i need to get xml element values and using that values i need to insert it in db. Any help would be appreciated.
XML:
<ListInventorySupplyResponse xmlns="http://mws.amazonaws.com/FulfillmentInventory/2010-10-01/">
- <ListInventorySupplyResult>
- <InventorySupplyList>
- <member>
<SellerSKU>043859634910</SellerSKU>
<FNSKU>X000IA4045</FNSKU>
<ASIN>B005YV4DJO</ASIN>
<Condition>NewItem</Condition>
<TotalSupplyQuantity>10</TotalSupplyQuantity>
<InStockSupplyQuantity>10</InStockSupplyQuantity>
- <EarliestAvailability>
<TimepointType>Immediately</TimepointType>
</EarliestAvailability>
<SupplyDetail />
</member>
</InventorySupplyList>
</ListInventorySupplyResult>
- <ResponseMetadata>
<RequestId>d50af29d-f203-4efc-a864-1725a59ded97</RequestId>
</ResponseMetadata>
</ListInventorySupplyResponse>
Code:
XDocument xd = XDocument.Parse(a);
string Sku = xd.Element();
var ASIN = xd.Descendants("ASIN");
var Condition = xd.Descendants("Condition");
var TotalSupplyQuantity = xd.Descendants("TotalSupplyQuantity");
You should use the xml namespace http://mws.amazonaws.com/FulfillmentInventory/2010-10-01/
var xDoc = XDocument.Parse(xml);
XNamespace ns = "http://mws.amazonaws.com/FulfillmentInventory/2010-10-01/";
var condition = (string)xDoc.Descendants(ns + "Condition").First();
OR
you can search for Tag Condition in any xml namespace
var condition2 = (string)xDoc.Descendants()
.First(d => d.Name.LocalName == "Condition");
OR
you can use XPath to get Condition in any xml namespace
var condition3 = (string)xDoc.XPathSelectElement("//*[local-name()='Condition']");
Use this:
string value = xd.Root.Element("SellerSKU").Value;
Here is the XML sample:
<?xml version="1.0" ?>
<XMLScreen xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CX>80</CX>
<CY>24</CY>
<Formatted>true</Formatted>
<Field>
<Location position="1" left="1" top="0" length="69" />
<Attributes Base="226" Protected="false" FieldType="High" />
*SDC SCHEDULING CATEGORY UPDATE
</Field>
</XMLScreen>
I want to retrive the Inner text of each field based on its Location position.
What I have so far is:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(myEm.CurrentScreenXML.GetXMLText());
XmlNodeList fields = xmlDoc.GetElementsByTagName("Field");
MessageBox.Show("Field spot: " + i + " Contains: " + fields[i].InnerText);
And I want to be able to just extract the inner text of the field by passing in a number of the location position. So if I say foo[i] I want to be able to get the innertext
*SDC SCHEDULING CATEGORY UPDATE
You should use a xpath search query :
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
int nodeId = 4;
XmlNode node = xmlDoc.SelectSingleNode(String.Format(#"//Location[#position='{0}']", nodeId));
if (node != null)
{
String field = node.ParentNode.InnerText;
}
Something like that, with XDocument instead of XmlDocument (well, if you're not in .net 3.5 or higher, we'll have a problem).
private string GetTextByLocationId(XDocument document, int id)
{
var field = document.Descendants("Field").FirstOrDefault(m => m.Element("Location").Attribute("position").Value == id.ToString());
if (field == null) return null;
return field.Value;
}
and usage
var xDocument = XDocument.Load(<pathToXmlFile or XmlReader or string or ...>);
var result = GetTextByLocationId(xDocument, 1);
EDIT
or if you want a dictionary with :key = position / value = text
private static Dictionary<int, string> ParseLocationAndText(XDocument document)
{
var fields = document.Descendants("Field");
return fields.ToDictionary(
f => Convert.ToInt32(f.Element("Location").Attribute("position").Value),
f => f.Value);
}
Try,
XElement root = XElement.Parse(myEm.CurrentScreenXML.GetXMLText());
XElement field = root.XPathSelectElement(
string.Format("Field[Location/#position='{0}']", 1));
string text = field.Value;
You will need to use the following using to use XPath with XElements.
using System.Xml.XPath;