How to use SetElementValue on XDocument - c#

This is the sample of my xml
<?xml version="1.0"?>
<SearchHistory>
<Search>
<title>Text 1</title>
<count>0</count>
</Search>
<Search>
<title>Text 2</title>
<count>0</count>
</Search>
</SearchHistory>
And I want to change the value of count of Text 1
this is what i tried:
xdoc.Descendants("Search")
.Where(x => x.Element("title").Value == tbSearch.Text)
.Single().SetElementValue("count", curCount);

You have to Save the XDocument when you have made changes
xDoc.Save(fileName);

xdoc.Descendants("Search")
.Where(x => x.Element("title").Value == tbSearch.Text)
.Single()
.Descendants("count")
.Single()
.Value = "1";

Related

How to read values from this XML

I'm trying to read the xml from a soap response. It is given below
`<OTA_AirLowFareSearchRS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Version="1.9.2" PricedItinCount="1" BrandedOneWayItinCount="0" SimpleOneWayItinCount="0" DepartedItinCount="0" SoldOutItinCount="0" AvailableItinCount="0">
<Success xmlns="http://www.opentravel.org/OTA/2003/05"/>
<Warnings xmlns="http://www.opentravel.org/OTA/2003/05">...</Warnings>
<PricedItineraries xmlns="http://www.opentravel.org/OTA/2003/05">
<PricedItinerary SequenceNumber="1">
<AirItinerary DirectionInd="OneWay">
<OriginDestinationOptions>
<OriginDestinationOption ElapsedTime="1920">
<FlightSegment DepartureDateTime="2017-03-21T21:45:00" ArrivalDateTime="2017-03-22T09:50:00" StopQuantity="0" FlightNumber="7336" ResBookDesigCode="T" ElapsedTime="425">
<DepartureAirport LocationCode="CDL" TerminalID="1"/>
<ArrivalAirport LocationCode="CDA" TerminalID="1A"/>
<OperatingAirline Code="AA" FlightNumber="810"/>
<Equipment AirEquipType="000"/>
<MarketingAirline Code="PP"/>
<DisclosureAirline Code="AC"/>
<MarriageGrp>O</MarriageGrp>
<DepartureTimeZone GMTOffset="-10"/>
<ArrivalTimeZone GMTOffset="11"/>
<TPA_Extensions>
<eTicket Ind="true"/>
</TPA_Extensions>
</FlightSegment>
</OriginDestinationOption>
</OriginDestinationOptions>
</AirItinerary>
</PricedItinerary>
</PricedItineraries>
</OTA_AirLowFareSearchRS>`
I've tried a lot of stuff with LINQ to XML, but nothing seems to work.
Here's a sample i've tried using
var xml = XDocument.Parse(stringXMLResponse);
var result = from item in xml.Descendants("FlightSegment")
select new
{
v1 = item.FirstAttribute.Value
};
Any suggestions would be encouraged. Thank you.
You can write your LINQ query like this. You may need to tweak it your requirement but it works with your XML string.
var selected = from x in xdoc.Descendants()
where x.NodeType == XmlNodeType.Element
&& x.Name.LocalName == "FlightSegment"
select x;
Here is fiddler : https://dotnetfiddle.net/NxkT38

C#: Check particular attribute key-value pair is present using linq

I want to check whether a particular attribute key-value pair is present using linq.
I am using following code to check:
bool keyPresent = xDocument.Element("noSqlDb").Element("elements").Elements("key")
.Where(el => el.Attribute("id").Equals(key.ToString()))
.Any();
My XML looks like below:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<noSqlDb>
<keytype>System.Int32</keytype>
<payloadtype>a</payloadtype>
<elements>
<key id="1">
<name>element</name>
<descr>test element</descr>
<timestamp>2015-10-02T23:54:07.6562371-04:00</timestamp>
<children>
<item>1</item>
<item>2</item>
<item>3</item>
</children>
<payload>
<item>CSE681</item>
<item>SMA</item>
<item>C#.net</item>
</payload>
</key>
</elements>
</noSqlDb>
You could simply use Xpath to try to find the element.
bool keyPresent = xDocument.XPathSelectElement(String.Format("//key[#id={0}]", key)) != null;
..or using LINQ
bool keyPresent = xDocument.Descendants()
.Any(e => e.Name == "key" && e.Attributes()
.Any(a => a.Name == "id" && a.Value == key.ToString()));

How do I parse text from complex type xml in c# using XDocument?

<?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"];

Delete xElement by xAttribute value

I have the following xml document:
<?xml version="1.0" encoding="utf-8"?>
<Categories>
<title>
<Type name="James">
<Field name="ref" value="79" />
<Field name="titleref" value="55" />
</Type>
</title>
</Categories>
I want to delete all of 'title' if the textBox1 text matches
I have the following, I know it doesn't work, but I wanted to see if you can see my logic.
xmldoc.Root.Elements().Where(x => x.Element("Type")).Where (x => x.Attribute("name").Value.Equals(textBox1.Text)).Select(x => x).Single().Remove();
Any help would be great
Thanks
You can use XPath (System.Xml.XPath)
xmldoc.XPathSelectElements(String.Format("//Type[#name='{0}']", textBox1.Text))
.Remove();
xmldoc.Root.Descendants( "Type" )
.Where( x => x.Attribute( "name" ).Value == textBox1.Text )
.Remove();

Remove all text nodes from XML file

I want to remove all text nodes (but not any other type of node) from an XML file. How can I do this?
Example Input:
<root>
<slideshow id="1">
<Image>hii</Image>
<ImageContent>this</ImageContent>
<Thumbnail>is</Thumbnail>
<ThumbnailContent>A</ThumbnailContent>
</slideshow>
<slideshow id="2">
<Image>hii</Image>
<ImageContent>this</ImageContent>
<Thumbnail>is</Thumbnail>
<ThumbnailContent>B</ThumbnailContent>
</slideshow>
</root>
Expected Output:
<root>
<slideshow id="1">
<Image></Image>
<ImageContent></ImageContent>
<Thumbnail></Thumbnail>
<ThumbnailContent></ThumbnailContent>
</slideshow>
<slideshow id="2">
<Image></Image>
<ImageContent></ImageContent>
<Thumbnail></Thumbnail>
<ThumbnailContent></ThumbnailContent>
</slideshow>
</root>
How about:
var doc = XDocument.Load("test.xml");
doc.DescendantNodes()
.Where(x => x.NodeType == XmlNodeType.Text ||
x.NodeType == XmlNodeType.CDATA)
.Remove();
doc.Save("clean.xml");
EDIT: Note that the above was before I realized that XCData derived from XText, leading to the simpler:
var doc = XDocument.Load("test.xml");
doc.DescendantNodes()
.OfType<XText>()
.Remove();
doc.Save("clean.xml");
This question should help: Linq to XML - update/alter the nodes of an XML Document
You can use Linq to open the document and alter the values or remove the nodes altogether.

Categories

Resources