Building xml from scratch and getting result in string? - c#

I'm trying to build up xml document from scratch with use linq-to-xml.
XElement root = new XElement("RootNode");
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", ""), root
);
for (int j = 0; j < 10; j++)
{
XElement element = new XElement("SetGrid");
element.SetElementValue("ID", j);
root.Add(element);
}
var reader = doc.CreateReader();//doc has 10 elements inside root element
string result = reader.ReadInnerXml();//always empty string
How can I get string from XDocument?

Just use string result = doc.ToString() or
var wr = new StringWriter();
doc.Save(wr);
string result = wr.ToString();

One option for empty string as per documentation.
XmlReader return:
All the XML content, including markup, in the current node. If the
current node has no children, an empty string is returned. If the
current node is neither an element nor attribute, an empty string is
returned.
try:
XmlReader reader = doc.CreateReader();
reader.Read();
string result = reader.ReadInnerXml()

var wr = new StringWriter();
doc.Save(wr);
var xmlString = wr.GetStringBuilder().ToString());

There's a full answer is here.
Long story short, you're missing reader.MoveToContent();
i.e. it should be:
var reader = root.CreateReader();
reader.MoveToContent(); // <- the missing line
string result = reader.ReadInnerXml();
This way the result won't be empty and you even don't have to create XDocument
So the full code from the original question + the fix is:
XElement root = new XElement("RootNode");
for (int j = 0; j < 10; j++)
{
XElement element = new XElement("SetGrid");
element.SetElementValue("ID", j);
root.Add(element);
}
var reader = root.CreateReader();// root has 10 elements
reader.MoveToContent(); // <-- missing line
string result = reader.ReadOuterXml(); // now it returns non-empty string
Output:
<RootNode><SetGrid><ID>0</ID></SetGrid><SetGrid><ID>1</ID></SetGrid><SetGrid><ID>2</ID></SetGrid><SetGrid><ID>3</ID></SetGrid><SetGrid><ID>4</ID></SetGrid><SetGrid><ID>5</ID></SetGrid><SetGrid><ID>6</ID></SetGrid><SetGrid><ID>7</ID></SetGrid><SetGrid><ID>8</ID></SetGrid><SetGrid><ID>9</ID></SetGrid></RootNode>
Note: The code is tested in Visual Studio 2013 / .NET Framework 4.5
MDSN Reference: XmlReader.ReadOuterXml

Related

add new lines when generating xml from object

this is the code
XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("customers");
xml.AppendChild(root);
foreach (var cust in customerlist)
{
XmlElement child = xml.CreateElement("customer");
child.SetAttribute("CustomerId", cust.CustomerId.ToString());
child.SetAttribute("CustomerName", cust.CustomerName);
child.SetAttribute("PhoneNumber", cust.PhoneNumber);
child.SetAttribute("Email", cust.Email);
root.AppendChild(child);
}
string s = xml.OuterXml;
I want my string to have next lines added to it instead of a single xml document
My string is coming as continuous
< x >xxxxx< /x > < x >xxxxx< /x >
You can use the XmlTextWriter class to format the XML as a string like this:
StringWriter string_writer = new StringWriter();
XmlTextWriter xml_text_writer = new XmlTextWriter(string_writer);
xml_text_writer.Formatting = Formatting.Indented;
xml.WriteTo(xml_text_writer); // xml is your XmlDocument
string formattedXml = string_writer.ToString();

Extracting XML tags values

I have a list of XML files that I need to extract 3 values from each file.
The XML looks somewhat like :
<ClinicalDocument xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" moodCode="EVN" xmlns="urn:hl7-org:v3">
<title>Summary</title>
<recordTarget>
<patientRole>
<patient>
<name>
<given>John</given>
<given>S</given>
<family>Doe</family>
</name>
<birthTime value="19480503" />
I'm trying to extract given name, family name and birth time.
Initially I'm trying to print out the values using:
XmlDocument doc2 = new XmlDocument();
doc2.Load(#"Z:\\DATA\\file.XML");
XmlElement root = doc2.DocumentElement;
XmlNodeList list = root.GetElementsByTagName("name");
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list.Item(i).Value);
}
I'm not getting any value printed, but when I debug and check the inner values of "list" I can see what I need from that tag.
How can I extract the needed information?
Your code and all other answers ignore the default namespace xmlns="urn:hl7-org:v3"
I find Linq2Xml easier to use, so I'll post an answer using it..
var xDoc = XDocument.Load(filename);
var #namespace = "urn:hl7-org:v3";
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xDoc.CreateNavigator().NameTable);
namespaceManager.AddNamespace("ns", #namespace);
XNamespace ns = #namespace;
var names = xDoc.XPathSelectElements("//ns:patient/ns:name", namespaceManager).ToList();
var list = names.Select(p => new
{
Given = string.Join(", ", p.Elements(ns + "given").Select(x => (string)x)),
Family = (string)p.Element(ns + "family"),
BirthTime = new DateTime(1970,1,1).AddSeconds( (int)p.Parent.Element(ns + "birthTime").Attribute("value"))
})
.ToList();
Try this instead:
XmlDocument doc2 = new XmlDocument();
doc2.Load(#"Path\To\XmlFile.xml");
XmlElement root = doc2.DocumentElement;
XmlNodeList list = root.GetElementsByTagName("name");
var names = list[0].ChildNodes;
for (int i = 0; i < names.Count; i++)
{
Console.WriteLine(names[i].InnerText);
}
Output:
John
S
Doe
There are 2 issues with your code:
The first being that you were iterating around the name element, which only has a Count of 1 (as there is only one of these). That's why I included list[0],ChildNodes, to get all the children of the name element (given, given and family).
To retrieve the text inside each element, ("John", "S", "Doe"), you should use InnerText instead of Value
It's not clear from your example XML if there is only ever one <name> element or if there could be multiple. The following assumes there might be multiple. It also grabs the birthdate.
for (int i = 0; i < list.Count; i++)
{
var xmlNode = list.Item(i).FirstChild;
while (xmlNode != null)
{
Console.WriteLine(xmlNode.InnerText);
xmlNode = xmlNode.NextSibling;
}
}
XmlNodeList birthDates = root.GetElementsByTagName("birthTime");
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(birthDates[i].Attributes["value"].Value);
}
If there are multiple <patient> elements in your xml you could do:
using System;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
class Program
{
static void Main()
{
var doc = XDocument.Load("a.xml");
var nsm = new XmlNamespaceManager(new NameTable());
nsm.AddNamespace("x", "urn:hl7-org:v3");
var patients = doc.XPathSelectElements("//x:patient", nsm);
foreach (var patient in patients)
{
Console.WriteLine(patient.XPathSelectElement("./x:name/x:given[1]", nsm).Value);
Console.WriteLine(patient.XPathSelectElement("./x:name/x:given[2]", nsm).Value);
Console.WriteLine(patient.XPathSelectElement("./x:name/x:family", nsm).Value);
Console.WriteLine(patient.XPathSelectElement("./x:birthTime", nsm).Attribute("value").Value);
}
}
}
Why do you need to add the name space explicitly even if it's a default name space in the xml? see: this answer

Can't get attribute value with C# XPath

I've spent so much time with this already, still can't get the value of NTE attribute. Can someone please help?
C#
StreamReader sr = new StreamReader(resp.GetResponseStream());
XPathDocument xmlDoc = new XPathDocument(sr); // holds xml document
XPathNavigator xmlNav = xmlDoc.CreateNavigator(); //evaluates XPath expressions
XPathNodeIterator node = xmlNav.Select("/DATA2SC/CALL");
string dne = xmlNav.GetAttribute("NTE", "");
Console.WriteLine(dne);
sr.Close();
XML
<?xml version="1.0"?>
<DATA2SC PIN="00000">
<CALL
TR_NUM="00000001"
STATUS="WAITING_FOR_APPROVAL"
NTE="$15.00">
<PROBLEM>
Text
</PROBLEM>
</CALL>
</DATA2SC>
Can you try this code please ?
I already check and it's work
StreamReader sr = new StreamReader("c:\\x.xml");
XPathDocument xmlDoc = new XPathDocument(sr); // holds xml document
XPathNavigator xmlNav = xmlDoc.CreateNavigator(); //evaluates XPath expressions
var node = xmlNav.SelectSingleNode("/DATA2SC/CALL");
string dne = node.GetAttribute("NTE", "");
Console.WriteLine(dne);
OR
XDocument docXmlWorld = XDocument.Load("c:\\x.xml");
foreach (var node1 in docXmlWorld.Descendants("DATA2SC"))
{
foreach (var node2 in node1.Descendants("CALL"))
{
string dne = node2.Attribute("NTE").Value;
Console.Out.WriteLine(dne);
}
}
Or you can do like this too:
XDocument docXmlWorld = XDocument.Load("c:\\x.xml");
//Get the first child => [DATA2SC]
XElement elementNodeDATA2SC = docXmlWorld.Element("DATA2SC");
//Get the first child => [CALL]
XElement elementNodeCALL = elementNodeDATA2SC.Element("CALL");
//Get the attribute NTE from [CALL] node
string dne = elementNodeCALL.Attribute("NTE").Value;
Console.Out.WriteLine(dne);
The Select method, returns a collection of all nodes with the specified XPath.
You can use SelectSingleNode, to select the first node.
var node = xmlNav.SelectSingleNode("/DATA2SC/CALL");
string dne = node.GetAttribute("NTE", "");

Inserting data at specific position in XML

I want to read an XML file and match tag </contrib-group> and write a string after this tag
string Final = File.ReadAllText(Npath);
string Oxml = path + "\\" + Oword + ".abs.xml";
if (File.Exists(Oxml))
{
StreamReader xml = new StreamReader(Oxml,Encoding.UTF8);
string xmltag = xml.ReadToEnd();
//File.OpenWrite(Oxml);
xml.Close();
StreamWriter write = new StreamWriter(Oxml, true, Encoding.UTF8);
Match tag = Regex.Match(xmltag, #"</contrib-group>");
if (tag.Success == true)
{
write.WriteLine(Environment.NewLine);
write.Write(Final);
}
}
So I need to write the string Final to the XML file called Oxml after the matched XML tag </contrib-group>
If you are willing to save the new content as a valid XML file which you can work with, you should use the XML classes for that approach, this should look like this (untested):
XmlDocument doc = new XmlDocument();
doc.Load("YourFile.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList elemList = root.GetElementsByTagName("contrib-group");
for (int i=0; i < elemList.Count; i++)
{
XmlNode xnode = elemList[i];
XmlNode xnodeParent = xnode.ParentNode;
XMLNode newNode = doc.CreateNode(XmlNodeType.Element, "NodeName", "");
newNode.InnerText = "ContentInsideTheNode";
xnodeParent.InsertAfter(newNode, xnode);
}
doc.Save("YourFile.xml");
If you only need to replace the string for other purposes than saving it where having a valid XML is not an issue you can just handle it as a string and use the String.Replace (String, String) Method
string searchedTag = #"</contrib-group>";
string tagAndNewContent = #"</contrib-group>" + newContent;
string fileContentString = File.ReadAllText("YourFile.xml");
string ouput = fileContentString.Replace(searchedTag, tagAndNewContent);

Loop through multiple subnodes in XML

<Sections>
<Classes>
<Class>VI</Class>
<Class>VII</Class>
</Classes>
<Students>
<Student>abc</Student>
<Student>def</Student>
</Students>
</Sections>
I have to loop through Classes to get 'Class' into an array of strings. I have to also loop through 'Students' to get 'Student' put into an array of strings.
XDocument doc.Load("File.xml");
string str1;
foreach(XElement mainLoop in doc.Descendants("Sections"))
{
foreach(XElement classLoop in mainLoop.Descendants("Classes"))
str1 = classLoop.Element("Class").Value +",";
//Also get Student value
}
is not working to get all the classes. Also, I need to rewrite this without using LINQ to XML, i.e using XmlNodeList and XmlNodes.
XmlDocument doc1 = new XmlDocument();
doc1.Load("File.xml");
foreach(XmlNode mainLoop in doc.SelectNodes("Sections")) ??
Not sure how to go about it.
The XPath is straightforward. To get the results into an array you can either use LINQ or a regular loop.
var classNodes = doc.SelectNodes("/Sections/Classes/Class");
// LINQ approach
string[] classes = classNodes.Cast<XmlNode>()
.Select(n => n.InnerText)
.ToArray();
var studentNodes = doc.SelectNodes("/Sections/Students/Student");
// traditional approach
string[] students = new string[studentNodes.Count];
for (int i = 0; i < studentNodes.Count; i++)
{
students[i] = studentNodes[i].InnerText;
}
Not sure about rewriting it for XmlNodes but for your Classes and Students you can simply:
XDocument doc.Load("File.xml");
foreach(XElement c in doc.Descendants("Class"))
{
// do something with c.Value;
}
foreach(XElement s in doc.Descendants("Student"))
{
// do something with s.Value;
}
With LINQ to XML:
XDocument doc = XDocument.Load("file.xml");
var classNodes = doc.Elements("Sections").Elements("Classes").Elements("Class");
StringBuilder result = new StringBuilder();
foreach( var c in classNodes )
result.Append(c.Value).Append(",");
With XPath:
XmlDocument doc = new XmlDocument();
doc.Load("file.xml");
var classNodes = doc.SelectNodes("/Sections/Classes/Class/text()");
StringBuilder result = new StringBuilder();
foreach( XmlNode c in classNodes )
result.Append(c.Value).Append(",");

Categories