How to get attribute in the XDocument object - c#

I have this xml
<config>
<audio first="true" second="false" third="true" />
</config>
I want my code to able to do something like this
if (xdoc.getAttr("first")=="true")
Console.Write("first is true");
How do I do this with LINQ XDocument?
What I have so far is the XDocument Object loaded with that xml string.

You need to get the attribute of the <audio> element:
string value = xdoc.Root.Element("audio").Attribute("first").Value;

You should take a look at XElement
article at c-sharpcorner.com

Related

find if a code exists in xml, using c#

I am starting to work with xml and I am trying to know if there is a way to search a code in this.
Here you are my xml
<?xml version="1.0" encoding="UTF-8"?>
<doctors_hospital>
<doctor>
<code>1757D</code>
<name>one</name>
</doctor>
<doctor>
<code>1169L</code>
<name>two</name>
</doctor>
... continues xml
</doctors_hospital>
I want to look for the code "aab" using c#, and this is my code..
var document =new XmlDocument();
document.Load("O:\\test\\doctor.xml");
XmlNode doctor;
XmlNode root = document.DocumentElement;
doctor = root.SelectSingleNode("/doctors_hospital/doctor/code='aab'");
I can not do this. any suggestion? thanks
Assuming SelectingSingleNode takes a standard XPath expression, what you want to use is
/doctors_hospital/doctor[code='aab']
This will select the entire doctor node with the matching code value.
I agree with Jim, alternatively you could also use Linq to Xml and do this.
XDocument doc = XDocument.Load(filepath);
var codeExist = doc.Descendants("code").Any(x=>(string)x.Value == "1169L");
Check this Demo

Linq2Xml Remove specific attribute name and their values

I have this XML, and i am trying to delete those:
Name="items"
Name="shipmentsShipmentIndex"
"Name" is not going to change,
The word that will be change is the word between the quotation marks, in this example:
items and shipmentsShipmentIndex
<?xml version="1.0" encoding="UTF-8"?>
<RootDTO xmlns:json='http://james.newtonking.com/projects/json'>
<destination>
<name>XXX</name>
</destination>
<orderData>
<items json:Array='true'>
<shipmentIndex Name="items">0</shipmentIndex>
</items>
<items json:Array='true'>
<shipmentIndex Name="items">0</shipmentIndex>
</items>
<shipments json:Array='true'>
<shipmentIndex Name="shipmentsShipmentIndex">0</shipmentIndex>
</shipments>
</orderData>
</RootDTO>
How can i find all these occurrences and remove them(or replace them with nothing)?
I tried a bunch of variations like: Name{1}[a-zA-Z]+"\b
You wrote this is ASP.NET. You can use Linq2Xml to perform this operation very quickly (LinqPad example):
void Main()
{
var test = XDocument.Parse("<root><node name=\"name value\">Text</node></root>");
foreach(var attr in test.Descendants().SelectMany(el=>el.Attributes("name")))
attr.Remove();
test.Dump();
}
So from this:
<root>
<node name="name value">Text</node>
</root>
You get this:
<root>
<node>Text</node>
</root>
The snippet will remove ALL name attributes from every single element in the XML aside of the root one. If you want to do something else (like just empty the attribute, or include the root element), let me know.
Don't parse XML with regular expressions. Use an XML aware tool.
For example, in xsh, you can achieve this with
open file.xml ;
rm //#Name ;
save :b ;
Try this RegEx:
Name=\"(.*?)\"

Change an XML node value

I have an xml document that looks like this
<?xml version="1.0"?>
<XML>
<VIDEO>
<WIDTH>800</WIDTH>
<HEIGHT>600</HEIGHT>
<COLORBITS>32</COLORBITS>
<GAMMA>255</GAMMA>
<FULLSCREEN>TRUE</FULLSCREEN>
<REFLECTION>true</REFLECTION>
<LIGHTMAP>true</LIGHTMAP>
<DYNAMICLIGHT>true</DYNAMICLIGHT>
<SHADER>true</SHADER>
<CHARACTORTEXTURELEVEL>0</CHARACTORTEXTURELEVEL>
<MAPTEXTURELEVEL>0</MAPTEXTURELEVEL>
<EFFECTLEVEL>0</EFFECTLEVEL>
<TEXTUREFORMAT>1</TEXTUREFORMAT>
<NHARDWARETNL>false</NHARDWARETNL>
</VIDEO>
</XML>
I want to change the value of the "MAPTEXTURELEVEL" node from 0 to 6 using the checked statement of a checkbox in a C# application, but I really have no idea of how I can do it.
I don't have VS to test it, but it should be something like this using LINQ to XML:
var doc = XDocument.Load("video.xml");
doc
.Element("XML")
.Element("VIDEO")
.SetElementValue("MAPTEXTURELEVEL", 6);
doc.Save("video_modified.xml");
Hope it helps!

How to access XML String values in C#?

I'm learning to use ReST Web services and I need to find out how to get a specific value from the xml string that is returned. How can I simply get 1 value from an xml String? All I want is one value. Is there some way to convert this string into something with an indexer?
I'm using Yahoo Geocoding service. Results:
<ResultSet version="1.0">
<Error>0</Error>
<ErrorMessage>No error</ErrorMessage>
<Locale>us_US</Locale>
<Quality>87</Quality>
<Found>1</Found>
−
<Result>
<quality>85</quality>
<latitude>86.457310</latitude>
<longitude>-73.262245</longitude>
<offsetlat>46.457311</offsetlat>
<offsetlon>-73.262071</offsetlon>
<radius>500</radius>
<name/>
<line1>1234 N Main St</line1>
<line2>Anytown, New York 12345</line2>
<line3/>
<line4>United States</line4>
<house>1234</house>
<street>N Main St</street>
<xstreet/>
<unittype/>
<unit/>
<postal>12345</postal>
<neighborhood/>
<city>New York</city>
<county>Albany County</county>
<state>New York</state>
<country>United States</country>
<countrycode>US</countrycode>
<statecode>NY</statecode>
<countycode/>
<uzip>12345</uzip>
<hash>E692D20CBDF86A2E</hash>
<woeid>12783988</woeid>
<woetype>11</woetype>
</Result>
</ResultSet>
You could use Linq to XML
XDocument xmlfile= XDocument.Load("PATH TO XML DOC");
var test = from xml in xmlfile.Descendants("item_name")
select new { Title = (string)xml.Element("title").Value };
That's one way.
Use XPath to address the node you are interested in:
http://msdn.microsoft.com/en-us/library/d271ytdx(v=VS.90).aspx
To transform XML string into an XML document
XmlDocument doc = new XmlDocument();
doc.LoadXml(yourString);
Here is a good introduction to XPath: http://www.codeproject.com/KB/cpp/myXPath.aspx
See my question on Easiest way to read XML with attributes. I found that using xsd.exe to generate a xsd which allows you managed access to the XML was the simplest way to access the XML data. LINQ2XML was also pretty easy to use.

XML Illegal Characters in path

I am querying a soap based service and wish to analyze the XML returned however when I try to load the XML into an XDoc in order to query the data. am getting an 'illegal characters in path' error message? This (below) is the XML returned from the service. I simply want to get the list of competitions and put them into a List I have setup. The XML does load into an XML Document though so must be correctly formatted?.
Any advice on the best way to do this and get round the error would be greatly appreciated.
<?xml version="1.0" ?>
- <gsmrs version="2.0" sport="soccer" lang="en" last_generated="2010-08-27 20:40:05">
- <method method_id="3" name="get_competitions">
<parameter name="area_id" value="1" />
<parameter name="authorized" value="yes" />
<parameter name="lang" value="en" />
</method>
<competition competition_id="11" name="2. Bundesliga" soccertype="default" teamtype="default" display_order="20" type="club" area_id="80" last_updated="2010-08-27 19:53:14" area_name="Germany" countrycode="DEU" />
</gsmrs>
Here is my code, I need to be able to query the data in an XDoc:
string theXml = myGSM.get_competitions("", "", 1, "en", "yes");
XmlDocument myDoc = new XmlDocument();
MyDoc.LoadXml(theXml);
XDocument xDoc = XDocument.Load(myDoc.InnerXml);
You don't show your source code, however I guess what you are doing is this:
string xml = ... retrieve ...;
XmlDocument doc = new XmlDocument();
doc.Load(xml); // error thrown here
The Load method expects a file name not an XML itself. To load an actual XML, just use the LoadXml method:
... same code ...
doc.LoadXml(xml);
Similarly, using XDocument the Load(string) method expects a filename, not an actual XML. However, there's no LoadXml method, so the correct way of loading the XML from a string is like this:
string xml = ... retrieve ...;
XDocument doc;
using (StringReader s = new StringReader(xml))
{
doc = XDocument.Load(s);
}
As a matter of fact when developing anything, it's a very good idea to pay attention to the semantics (meaning) of parameters not just their types. When the type of a parameter is a string it doesn't mean one can feed in just anything that is a string.
Also in respect to your updated question, it makes no sense to use XmlDocument and XDocument at the same time. Choose one or the another.
Following up on Ondrej Tucny's answer :
If you would like to use an xml string instead, you can use an XElement, and call the "parse" method. (Since for your needs, XElement and XDocument would meet your needs)
For example ;
string theXML = '... get something xml-ish...';
XElement xEle = XElement.Parse(theXML);
// do something with your XElement
The XElement's Parse method lets you pass in an XML string, while the Load method needs a file name.
Why not
XDocument.Parse(theXml);
I assume this will be the right solution
If this is really your output it is illegal XML because of the minus characters ('-'). I suspect that you have cut and pasted this from a browser such as IE. You must show the exact XML from a text editor, not a browser.

Categories