How do I read this xml File? - c#

I have this xml file
<?xml version="1.0" encoding="utf-8" ?>
<parameters>
<parameters
registerLink="linkValue"
TextBox.name="nameValue"
/>
</parameters>
I want to print off "LinkValue" and "nameValue" by code:
Console.WriteLine("registerLink: " + registerLink);
Console.WriteLine("TextBox.name: " + TextBox.name);
Thanks

The easiest API is XLinq (System.Xml.Linq)
var doc = XDocument.Load(fileName);
// This should be parameters/parameter, i follow the question with parameters/parameters
var par = doc.Element("parameters").Element("parameters");
registerLink = par.Attribute("registerLink").Value; // string

Your could use an xml reader like this one
http://msdn.microsoft.com/en-us/library/cc189056%28v=vs.95%29.aspx
Once you have a working sample look here to find out how to open an xml reader from a file stream. File must be located in project directory
http://support.microsoft.com/kb/307548
Once you have that done you can add an open file dialog box to find any file on the computer and even validate the .xml extension and more.
Edit: As you can see in the comments below, Hanks solution is better, faster, and easier. My solution would only be useful if you have huge xml files with tons of data. You may still be interested in the file dialog box as well.

Related

c# File in xml format not opening in xml viewer

Created a .xml file in C# console program using StreamWriter without using any xml write library functions). However, it does not show data in XML viewer - shows fine if opened as a text file.
I tried, like I saw somewhere on this site, the following -
FileStream fStream = new FileStream (#"c:\new.xml", FileMode.Create)
StreamWriter fWrite = new StreamWriter(fStream, Encoding.UTF8);
fwrite.WriteLine (myLine);
where the first myLine was
<?xml version="1.0" encoding="UTF-8"?>
Is there a way to make this open like an xml file without having to use the xml lib functions?
Here's some more info -
Contents of the file I wrote, as it opens in Notepad :
(OK, the contents are like below, but formatting isn't - the CTRL K that I was instructed to do here did the formatting!)
<?xml version="1.0" encoding="UTF-8"?>
<OutermostTag>
<RepetitiveInnerTag Action="AddSomething">
<ID1>12345<ID1>
<Level1>Leveldata1<Level1>
<DisplayName>Name to Display<DisplayName>
<Description>Describe it all here<Description>
<SortOrder>ASC<SortOrder>
<ID2>C3<ID2>
<Level2>Data<Level2>
</RepetitiveInnerTag>
</OutermostTag>
While opened as xml only the first inner tag (viz.,) data is displayed, space-demited as follows:
12345 Leveldata1 Name to Display Describe it all here ASC C3 Data
And the output display is the same whether I use the Encoding.UTF8 property or not.
By "open like an xml" I mean, in addition to displaying the entire data in the file, also make the tags collapsible (the color and all that format-related stuff that (presumably) the browser (IE) puts in)
Have you tried using flush? try putting it after fWrite.WriteLine
fWrite.Flush();
OK guys, I found out the blunder I did - didn't used the opening element tags to close them as well (OOOOPs!).Than you all for your time (and apologize to have wasted it too). a C/C++ programmer on my first C# trial project, didn't want the complications of using the XML writer libs; and now am delighted that it still works doing the lib work simply by myself the C-style (contrary to my boss's insistence that it wont:)). Will be careful next time I post

How to search through XML to find bad nodes

I have a large XML file (68Mb), I am using SQL Server Business Intelligence Studio 2008 to extract the XML data into a database. There is an error in the XML file some where that prevents it from executing. Possibly a missing tag or something like that. The file is so large I cant manually sort through it looking for the error.
Below is a sample of the the XML schema used.
How can I use XPath to sort through the XML in VS 2012 using C#?
An example would be great!
-<PhoneNumberList>
<PhoneNumber value="1234567890" type="Phone"/>
</PhoneNumberList>
-<YearsOfServiceList>
<YearsOfService experienceInMonths="24" description="SuperAdmin" objectCode="049"/>
</YearsOfServiceList>
</Person>
-<Person dob="1960-01-09T00:00:00" lastName="Smith" middleName="Will" firstName="John" id="9999-9999-9999">
-<SiteList>
-<Site id="2014" siteLongName="HA" siteCode="1255" systemCode="999">
-<StaffPositionList>
<StaffPosition id="73" staffPosition="Administrator"/>
</StaffPositionList>
</Site>
</SiteList>
-<ProgramList>
<Program id="1234" siteLongName="ABC" siteCode="0000" systemCode="205"/>
<Program id="5678" siteLongName="DEF" siteCode="0000" systemCode="357"/>
</ProgramList>
-<TypeList>
<Type Description="Leader" certificateType="D"/>
<Type Description="Professional" certificateType="P"/>
</TypeList>
-<EmailList>
<Email value="jsmith#somesite.com" type="Email"/>
</EmailList>
-<PhoneNumberList>
<PhoneNumber value="1234567890" type="Phone"/>
</PhoneNumberList>
-<YearsOfServiceList>
<YearsOfService experienceInMonths="24" description="SuperAdmin" objectCode="049"/>
</YearsOfServiceList>
</Person>
</PersonList>
</GetPersonDetail>
If you want to do it in code then create an XSD file describing a valid format for the data, embed it as a resource in your app and then use code like this
var errors = new List<string>();
var schemaSet = new XmlSchemaSet();
schemaSet.Add("", XmlReader.Create(new StringReader(Properties.Resources.NameOfXSDResource)));
document.Validate(schemaSet, (sender, args) =>
{
errors.Add(args.Message);
}
);
This will give you a list of validation errors.
You don't need to search "by hand" if you use a competent text editor. NotePad++'s XML plugin, for instance, can determine if your XML as a whole is well-formed or valid, and both instances will provide separate error messages.
If you don't have a schema and the file is well-formed, you can use the CLR's System.XML namespace to read in the document and then iterate through its nodes using LINQ-to-XML, which would allow you to very finely control which nodes go where. With LINQ, you could either create a new XML file with only the valid entries, procedurally correct the invalid entries as you determine where they are, or even just write to your SQL server database directly.
Your troubleshooting process should be something as follows:
Is the XML well-formed? I..e, does it comport to the fundamental rules of XML?
Is the XML valid? I.e., does it have the elements and attributes you expect?
Is your import query accurate?
For things like this I usually have luck checking and fixing the data in Notepad++. Install the XmlTools plugin and that has a menu for checking the xml syntax and tags.
Also, those dashes will give you problems, it's best to save out the xml file directly without copying by hand.
A 68MB XML file is no problem for XML editors such as XMLBlueprint 64-bit (http://www.xmlblueprint.com/) or Stylus Studio (http://www.stylusstudio.com/). Just check the well-formedness of your xml file (F7 in XMLBlueprint) and the editor will display the errors.

how to get xml content and edit xml file by using C#

I have an XML file called Emails.xml:
<Root>
<Emails>
<address>dfg#fds.com</address>
</Emails>
<Emails>
<address>adsfZSdf#.com</address>
</Emails>
</Root>
Um...I'm using visual studio, asp.net. I want to get the addresses by using C# code and also edit one or more addresses(e.g. chage "dfg#fds.com" to "ddfla#fds.com").
Furthermore, add new address(es) to this xml file.
(path of xml file is: C:\Documents and Settings\Administrator\Desktop\Emails.xml)
How can I do that?
Use the XmlDocument class. Then you can filter to the addresses with a call to GetElementsByTagName(string). From there, modification should be easy.

Programmatic XML Diff / Merge in C#

At this moment, I am managing a piece of software that has multiple XML configuration files. When a new version of software is released, sometimes the base config files change, we currently have the software call KDiff on startup. If it detects a change, it prompts the user to choose the changes.
The problem with this approach is that KDiff is a line comparing program and not aware of the ways of XML (like Nodes, etc.)
Ideally, I would like to programmatically work with a library in C# (since we're a MS shop) that can Diff two XML files: a Source XML and a Current Working XML.
And then Merge the two together using a few simple rules:
If the Current Working XML has a node that the Source XML does not, remove it.
If the Source XML has a node that the Current Working XML does not, add it.
If both have the same node and the values differ, favor the Source XML's value, unless it the Source XML's value is set to "UseExistingValue".
For example, here's the "Source" XML:
<Configuration>
<Items>
<Item Id="1" Position="true">
<Location X="UseExistingValue" Y="UseExistingValue" Z="UseExistingValue" />
<Something/>
<SomethingElse/>
</Item>
</Items>
</Configuration>
And here's the "Current Working" XML:
<Configuration>
<Items>
<Item Id="1" Position="false">
<Location X="123" Y="234" Z="345" />
<Another/>
<Something/>
</Item>
</Items>
</Configuration>
And the merged version would look like:
<Configuration>
<Items>
<Item Id="1" Position="true">
<Location X="123" Y="234" Z="345" />
<Something/>
<SomethingElse/>
</Item>
</Items>
</Configuration>
I've looked at the MS XML Diff and Patch Tool and it definitely merges the files together, but doesn't allow for the programmatic rules that I want to define.
XMLUnit for Java devs seems promising, but the .NET version of it seems underdeveloped, which is unfortunate.
Anyone have any suggestions for either scriptable XML Diff/Merge tools and/or .NET libraries (paid or free)?
Thanks.
After a couple days of messing around, I found a solution that I think works for me. Maybe it could work for other people as well.
The MS XML Diff and Patch tool was a viable option. When you Diff first file against the second file it creates an XML "DiffGram" listing what changes it detected between the two XML files.
To take care of all 3 rules that I listed above, I Diff'd the two files in one direction, then opened the DiffGram file using Linq-to-XML and Removed all the "Add" and "Remove" lines.
XNamespace xd = "http://schemas.microsoft.com/xmltools/2002/xmldiff";
var doc = XDocument.Load(_diffGramFile);
doc.Root.DescendantsAndSelf(xd + "add").Remove();
doc.Root.DescendantsAndSelf(xd + "remove").Remove();
Then I patched up (merged) this edited diffgram against the first file and created a partially merged temporary file. This takes care of Rules 1 and 2.
Next, I Diff'd the partially merged file against the first file used. Then opened the new DiffGram and removed all Change references to "UseExistingValue".
var newdoc = XDocument.Load(_diffGramFile);
newdoc.Root.DescendantsAndSelf(xd + "change")
.Where(x => x.Value == "UseExistingValue").Remove();
And merged this edited DiffGram against the partially merged file which takes care of Rule 3. Saving this out to XML then produces the final XML merged according to the rules defined above.
Hopefully this can help out other people.
HINT: After installing the XmlDiffPatch library, the XmlDiffPatch DLL can be found in C:\Windows\assembly\GAC\XmlDiffPatch\1.0.8.28__b03f5f7f11d50a3a\XmlDiffPatch.dll

Replace a word in an XML file through StreamReader in XNA?

Okay, so this is sort of a hack...but it may have to be. I'm writing an app in XNA, which from my research into this problem apparently doesn't support XML version 1.1. I'm reading in the contents of an ePub document, and one of the newer books encodes its content as a version 1.1 XML document. This causes my program to crash, however, the structure is the same as the rest. The only thing that is keeping it from working is the hard-coded "1.0" in the XmlDocument class.
Is it possible that I could read in the file from the stream, see if it contains:
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
and simply replace it with "1.0"? Then I could pull it in as an XmlDocument. I'm not doing any writing to the file, or any complex structural reading, just looking for a few specific nodes, and pulling in the values, so I don't know what the ramifications of this would be.
You can do this in a very dodgy way by reading the entire XML file into memory and having your way with it:
string content = "";
// Read the XML file into content
StreamReader reader = new StreamReader("file.xml");
content = reader.ReadToEnd();
reader.Close();
// Find the character position just after the <?xml token, and just before the ?> token
int openIndex = content.IndexOf("<?xml", StringComparison.OrdinalIgnoreCase) + 5;
int closeIndex = content.IndexOf("?>", openIndex);
// Get the bits between <?xml and ?>
string header = content.Substring(openIndex, closeIndex - openIndex);
// Substitute version string.
header = header.Replace("version=\"1.1\"", "version=\"1.0\"");
// Put Humpty Dumpty back together again.
content = string.Concat(content.Substring(0, openIndex), header, content.Substring(closeIndex));
// Feed content into an XMLReader (or equivalent) here.
It works for the example string you provide, but I haven't tested it on imperfectly-formatted XML documents.

Categories