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
Related
I'm kind of new to XML files in C# ASP.NET. I have a XML in the below format:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Installation>
<ServerIP>192.168.20.110</ServerIP>
<DB_Name>USTCKT1</DB_Name>
<Username>jorame</Username>
<Password>Cru$%e20</Password>
<Table_PreFix>TCK</Table_PreFix>
</Installation>
I need to change the values within each element. For example, when an user clicks I should be able to replace 192.168.20.110 with 192.168.1.12.
How can I accomplish this? Any help will be really appreciated.
You should look at using the methods in the XDocument class. http://msdn.microsoft.com/en-us/library/bb301598.aspx
Specifically look at the methods: Load(string) - to load an XML file, Element() - to access a specific element and Save(string) - to save the XML document. The page on Element() has some sample code which can help.
http://msdn.microsoft.com/en-us/library/system.xml.linq.xcontainer.element.aspx
You can do something like this using the XDocument class:
XDocument doc = XDocument.Load(file.xml);
doc.Element("Installation").Element("ServerIP").Value = "192.168.1.12";
//Update the rest of the elements
doc.Save(file.xml);
More Details
If you run into namespace issues when selecting your elements you will need to include the xml namespace in the XElement selectors eg doc.Element(namspace + "Installation")
In general, you can do it in the following steps:
Create a new XmlDocument object and load the content. The content might be a file or string.
Find the element that you want to modify. If the structure of your xml file is too complex, you can use xpath you find what you want.
Apply your modification to that element.
Update your xml file.
Here is a simple demo:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("file.xml"); // use LoadXml(string xml) to load xml string
string path = "/Installation/ServerIP";
XmlNode node = xmlDoc.SelectSingleNode(path); // use xpath to find a node
node.InnerText = "192.168.1.12"; // update node, replace the inner text
xmlDoc.Save("file.xml"); // save updated content
Hope it's helpful.
How to flat xml to one line in c# code ?
Before:
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
</CATALOG>
After:
<CATALOG><CD><TITLE>Empire Burlesque</TITLE><ARTIST>Bob Dylan</ARTIST>COUNTRY>USA</COUNTRY>....
Assuming you're able to use LINQ to XML, and the XML is currently in a file:
XDocument document = XDocument.Load("test.xml");
document.Save("test2.xml", SaveOptions.DisableFormatting);
If you cant use LINQ to XML, you can:
XmlDocument xmlDoc = new XmlDocument()
xmlDoc.LoadXml("Xml as string"); or xmlDoc.Load(filepath)
xmlDoc.InnerXml -- this should return one liner
If you have the XML in a string:
xml.Replace("\n", "").Replace("\r", "")
I know, that this is old question, but it helped me to find XDocument.ToString()
XDocument doc = XDocument.Load("file.xml");
// Flat one line XML
string s = doc.ToString(SaveOptions.DisableFormatting);
Check SaveOptions documentaion
Depends what you are working with and what output you need...
John Skeet's answer works if reading and writing to files.
Aleksej Vasinov's answer works if you want xml without the xml declaration.
If you simply want the xml in a string, but want the entire structure of the xml, including the declaration, ie..
<?xml version "1.0" encoding="utf-16"?> <-- This is the declaration ->
<TheRestOfTheXml />
.. use a StringWriter...
XDocument doc = GetTheXml(); // op's xml
var wr = new StringWriter();
doc.Save(wr, SaveOptions.DisableFormatting);
var s = wr.GetStringBuilder().ToString();
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.
Here's an example of an XML file created in InfoPath:
<?xml version="1.0" encoding="UTF-8"?>
<?mso-infoPathSolution solutionVersion="1.0.0.1" productVersion="12.0.0" PIVersion="1.0.0.0" href="file:///C:\Metastorm\Sample%20Procedures\InfoPath%20samples\Template1.xsn" name="urn:schemas-microsoft-com:office:infopath:Template1:-myXSD-2010-07-21T14-21-13" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<my:myFields xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-07-21T14:21:13" xml:lang="en-us">
<my:field1>hello</my:field1>
<my:field2>world</my:field2>
</my:myFields>
What are those top 3 nodes with the question mark called... and how do I create them in C#?
So far I have this:
XmlDocument xmldoc;
XmlDeclaration xmlDeclaration;
xmldoc=new XmlDocument();
xmlDeclaration = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "") as XmlDeclaration;
xmlDeclaration.Encoding = "UTF-8";
xmldoc.AppendChild(xmlDeclaration);
This works fine for the top XML declaration node , but how do I create the next two?
Thanks in advance :)
These are called processing instructions. Add 'em using XmlDocument.CreateProcessingInstruction.
Those are called processing instructions. You can use the XmlProcessingInstruction class to interact with them in an XmlDocument.
As with most elements defined within an XmlDocument, you cannot instantiate it directly; you must use the appropriate factory method on XmlDocument (CreateProcessingInstruction in that particular case.)
Thanks for explaining that these are processing instructions. Using CreateProcessingInstruction as suggested, here is the solution:
xmlPi = xmldoc.CreateProcessingInstruction("mso-infoPathSolution", "solutionVersion=\"1.0.0.1\" productVersion=\"12.0.0\" PIVersion=\"1.0.0.0\" href=\"file:///C:\\Metastorm\\Sample%20Procedures\\InfoPath%20samples\\Template1.xsn\" name=\"urn:schemas-microsoft-com:office:infopath:Template1:-myXSD-2010-07-21T14-21-13\"");
xmldoc.AppendChild(xmlPi);
I'm trying to access UPS tracking info and, as per their example, I need to build a request like so:
<?xml version="1.0" ?>
<AccessRequest xml:lang='en-US'>
<AccessLicenseNumber>YOURACCESSLICENSENUMBER</AccessLicenseNumber>
<UserId>YOURUSERID</UserId>
<Password>YOURPASSWORD</Password>
</AccessRequest>
<?xml version="1.0" ?>
<TrackRequest>
<Request>
<TransactionReference>
<CustomerContext>guidlikesubstance</CustomerContext>
</TransactionReference>
<RequestAction>Track</RequestAction>
</Request>
<TrackingNumber>1Z9999999999999999</TrackingNumber>
</TrackRequest>
I'm having a problem creating this with 1 XmlDocument in C#. When I try to add the second:
<?xml version="1.0" ?> or the <TrackRequest>
it throws an error:
System.InvalidOperationException: This
document already has a
'DocumentElement' node.
I'm guessing this is because a standard XmlDocument would only have 1 root node. Any ideas?
Heres my code so far:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
XmlElement rootNode = xmlDoc.CreateElement("AccessRequest");
rootNode.SetAttribute("xml:lang", "en-US");
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
xmlDoc.AppendChild(rootNode);
XmlElement licenseNode = xmlDoc.CreateElement("AccessLicenseNumber");
XmlElement userIDNode = xmlDoc.CreateElement("UserId");
XmlElement passwordNode = xmlDoc.CreateElement("Password");
XmlText licenseText = xmlDoc.CreateTextNode("mylicense");
XmlText userIDText = xmlDoc.CreateTextNode("myusername");
XmlText passwordText = xmlDoc.CreateTextNode("mypassword");
rootNode.AppendChild(licenseNode);
rootNode.AppendChild(userIDNode);
rootNode.AppendChild(passwordNode);
licenseNode.AppendChild(licenseText);
userIDNode.AppendChild(userIDText);
passwordNode.AppendChild(passwordText);
XmlElement rootNode2 = xmlDoc.CreateElement("TrackRequest");
xmlDoc.AppendChild(rootNode2);
An XML document can only ever have one root node. Otherwise it's not well formed. You will need to create 2 xml documents and join them together if you need to send both at once.
Its throwing an exception because you are trying to create invalid xml. XmlDocument will only generate well formed xml.
You could do it using an XMLWriter and setting XmlWriterSettings.ConformanceLevel to Fragment or you could create two XmlDocuments and write them out into the same stream.
Build two separate XML documents and concatenate their string representation.
It looks like your node structure always be the same. (I don't see any conditional logic.) If the structure is constant you could define an XML template string. Load that string into an XML Document & do a SelectNode to populate individual nodes.
That may be simpler/cleaner than programatically creating the root, elements & nodes.