I want to read the names form this xml:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://mysite.com/">
<name>2</name>
<name>3</name>
<name>4</name>
</string>
Tried:
var doc = XElement.Parse(s);
foreach (var v in doc.Descendants("name"))
{
//do work
}
but it does not work. Why?
Because you have a custom namespace - you need to specify the namespace when you select the elements - try this (tested and worked):
XNamespace xmlns = "http://mysite.com/";
var doc = XElement.Parse(s);
foreach (var v in doc.Descendants(xmlns + "name"))
{
//do work
}
Related
I need to change ALL the Tag name to Lowercase but leave the InnerText or Value as it is. I just found the thread showing how to change the casing for the entire document but NOT just for the Tag names.
Code
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlDoc.OuterXml.ToLower());
Original.xml
<?xml version="1.0" encoding="utf-8" ?>
<ROOT>
<InNeRtAg>SoMe TeXt</InNeRtAg>
<NeStEdElEmEnT>
<InNeRnEsTiNg>SoMe TeXt</InNeRnEsTiNg>
</NeStEdElEmEnT>
</ROOT>
Changing ALL nodes including the root element:
var doc = XDocument.Load("Original.xml");
// also need to change the root element
doc.Root.Name = doc.Root.Name.LocalName.ToLower();
foreach (var element in doc.Descendants().Elements())
{
element.Name = element.Name.LocalName.ToLower();
}
doc.Save("Modified.xml");
Results in Modified.xml
<?xml version="1.0" encoding="utf-8"?>
<root>
<innertag>SoMe TeXt</innertag>
<nestedelement>
<innernesting>SoMe TeXt</innernesting>
</nestedelement>
</root>
When using
foreach (var element in doc.Descendants().Elements())
{
element.Name = element.Name.LocalName.ToLower();
}
the root element will not be changed.
<?xml version="1.0" encoding="utf-8"?>
<ROOT>
<innertag>SoMe TeXt</innertag>
<nestedelement>
<innernesting>SoMe TeXt</innernesting>
</nestedelement>
</ROOT>
You can try something like this:
var doc = XDocument.Load(filepath);
foreach (var element in doc.Descendants().Elements())
{
element.Name = element.Name.LocalName.ToLower();
}
This is my xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!--Sample XML file generated by XMLSPY v5 rel. 4 U (http://www.xmlspy.com)-->
<decsts:EDI xmlns:decsts="http://www.testurl.com/schema/decsts" xmlns:cm="http://www.testurl.com/schema/common" xmlns:deccm="http://www.testurl.com/schema/deccm" xmlns:sau="http://www.testurl.com/schema/sau" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.testurl.com/schema/decsts
D:\sns\trade\sau\rel1_0\schemas\IDEC\decSTS.xsd" decsts:docType="DEC" decsts:id="SAU20160603187160" decsts:msgType="H2HDECSTS">
<decsts:record>
<sau:payload xsi:type="decsts:declarationStatusType">
<decsts:reference>
<decsts:userid>sdec001001</decsts:userid>
<decsts:acctId>rrni</decsts:acctId>
<decsts:docRefNo>20160603005992</decsts:docRefNo>
<decsts:regPort cm:type="4">23</decsts:regPort>
<deccm:declarationISN>1517791</deccm:declarationISN>
</decsts:reference>
<decsts:statusInformation>
<decsts:statusDate>2016-06-03</decsts:statusDate>
<decsts:statusCode>1</decsts:statusCode>
<decsts:originalMsgId>SAU20160603187153</decsts:originalMsgId>
</decsts:statusInformation>
<decsts:statusErrorDetails>
<decsts:statusErrorCodeDetails>4</decsts:statusErrorCodeDetails>
<decsts:remarks>goods are waiting for collection of customs fees</decsts:remarks>
</decsts:statusErrorDetails>
<decsts:statusErrorDetails>
<decsts:statusErrorCodeDetails>5</decsts:statusErrorCodeDetails>
<decsts:remarks>EXTRA NODE ERR</decsts:remarks>
</decsts:statusErrorDetails>
</sau:payload>
</decsts:record>
</decsts:EDI>
I am trying to iterate the xml file using following code:
XDocument xdoc = XDocument.Load("TEST_XML.xml");
XNamespace ns = "http://www.TESTURL.com/schema/decsts";
var datas = from query in xdoc.Descendants(ns + "statusErrorDetails")
select new
{
err_no = (string)query.Element(ns + "statusErrorCodeDetails"),
err_desc = (string)query.Element(ns + "remarks")
};
foreach (var item in datas)
{
Console.WriteLine(item.err_no);
Console.WriteLine(item.err_desc);
}
I am getting following output:
4 Error description 4
why it does not iterate next node and values of child. Please help me to solve this problem, thanks.
I solved the issue, I tried following code and it is giving me the output I want:
XmlNodeList err_details = xmlDoc.GetElementsByTagName("decsts:statusErrorDetails");
foreach (XmlNode err_node in err_details)
{
foreach (XmlNode err_items in err_node.ChildNodes)
{
Console.WriteLine(err_items.InnerText);
}
}
I have a XML document that's in the following format:
<?xml version="1.0" encoding="utf-8"?>
<?mso-infoPathSolution name="urn:schemas-microsoft-com:office:infopath:blah:-myXSD-2007-03-14T00-26-45" solutionVersion="1.0" productVersion="15.0.0.0" PIVersion="1.0.0.0" href="http://blah/FormServerTemplates/blah.xsn"?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.4"?>
<my:myFields xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls" xmlns:ma="http://schemas.microsoft.com/office/2009/metadata/properties/metaAttributes" xmlns:d="http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields" xmlns:q="http://schemas.microsoft.com/office/infopath/2009/WSSList/queryFields" xmlns:dms="http://schemas.microsoft.com/office/2009/documentManagement/types" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2007-03-14T00:26:45" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xml:lang="en-US">
<my:workDay>MON-FRI</my:workDay>
</my:myFields>
I tried to query the workday with the following code but got null.
var xdoc = XDocument.Load(file);
var workDay = from x in xdoc.Descendants("workDay")
select x.Value;
What did I do wrong?
you need to include the namespace for my::
var xdoc = XDocument.Load(file);
XNamespace myNamespace = "http://schemas.microsoft.com/office/infopath/2003/myXSD/2007-03-14T00:26:45";
var workDay = from x in xdoc.Descendants(myNamespace + "workDay")
select x.Value;
I have a problem, I can't get...and don't know what is wrong with it?
the code:
static void Main(string[] args)
{
XDocument doc = XDocument.Load(args[0] + "/?verb=GetRecord&metadataPrefix=p3dm&identifier=" + 1);
doc.Save("doc.xml");
var node = doc.Descendants("identifier");
foreach (var n in node)
{
doc.Save("file_" + n.Value + ".xml");
}
}
the doc.xml looks like:
<?xml version="1.0" encoding="utf-8"?>
<OAI-PMH xmlns="..." xmlns:xsi="..." xsi:schemaLocation="...">
<responseDate>...</responseDate>
<request verb="GetRecord" identifier="1"</request>
<GetRecord>
<record>
<header>
<identifier>1</identifier>
<datestamp>...</datestamp>
</header>
<metadata>
<P3DM xmlns="..." xsi:schemaLocation="...">
<MODELINFOID>1</MODELINFOID>
<TITLE>Roth</TITLE>
....
As we can see in doc.xml, there is element with the value 1, and using Descendants and foreach...I would like to save same document but using tag value to name my output file. What am I doing wrong. This code is just for testing.
Your XML has default namespace. You can use XNamespace plus element's local name to address an element in namespace :
......
//assume that the default namespace declared as <OAI-PMH xmlns="dummy.uri" ....>
XNamespace d = "dummy.uri";
var node = doc.Descendants(d+"identifier");
......
I would like to filter with high performance XML elements from an XML document.
Take for instance this XML file with contacts:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="asistentes.xslt"?>
<contactlist evento="Cena Navidad 2010" empresa="company">
<contact type="1" id="1">
<name>Name1</name>
<email>xxxx#zzzz.es</email>
<confirmado>SI</confirmado>
</contact>
<contact type="1" id="2">
<name>Name2</name>
<email>xxxxxxxxx#zzzze.es</email>
<confirmado>Sin confirmar</confirmado>
</contact>
</contaclist>
My current code to filter from this XML document:
using System;
using System.Xml.Linq;
class Test
{
static void Main()
{
string xml = #" the xml above";
XDocument doc = XDocument.Parse(xml);
foreach (XElement element in doc.Descendants("contact")) {
Console.WriteLine(element);
var id = element.Attribute("id").Value;
var valor = element.Descendants("confirmado").ToList()[0].Value;
var email = element.Descendants("email").ToList()[0].Value;
var name = element.Descendants("name").ToList()[0].Value;
if (valor.ToString() == "SI") { }
}
}
}
What would be the best way to optimize this code to filter on <confirmado> element content?
var doc = XDocument.Parse(xml);
var query = from contact in doc.Root.Elements("contact")
let confirmado = (string)contact.Element("confirmado")
where confirmado == "SI"
select new
{
Id = (int)contact.Attribute("id"),
Name = (string)contact.Element("name"),
Email = (string)contact.Element("email"),
Valor = confirmado
};
foreach (var contact in query)
{
...
}
Points of interest:
doc.Root.Elements("contact") selects only the <contact> elements in the document root, instead of searching the whole document for <contact> elements.
The XElement.Element method returns the first child element with the given name. No need to convert the child elements to a list and take the first element.
The XElement and XAttribute classes provide a wide selection of convenient conversion operators.
You could use LINQ:
foreach (XElement element in doc.Descendants("contact").Where(c => c.Element("confirmado").Value == "SI"))