I have a XElement as sample:
<trans-unit id="7655230f" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<source>EC<x id="0040" /><g id="0041"> test</g></source>
</trans-unit>
I want get inner text of tag source include sub tags:
EC<x id="0040" /><g id="0041"> test</g>
I had try this code, but it add xmlns into sub tag:
var oSource = oElement.XPathSelectElement(dNS + ":source", nsManager);
string source = String.Concat(oSource.Nodes());
Result:
EC<x id="0040" xmlns="urn:oasis:names:tc:xliff:document:1.2" /><g id="0041" xmlns="urn:oasis:names:tc:xliff:document:1.2"> エレシリンダ</g>
How can get inner text of a XElement include sub tags?
Probably the easiest way would be like this
var xml = XElement.Load("test.xml");
XNamespace ns = "urn:oasis:names:tc:xliff:document:1.2";
var sourceNode = xml.Element(ns + "source");
foreach (var node in sourceNode.DescendantNodesAndSelf().OfType<XElement>())
{
// remove namespace
node.Name = node.Name.LocalName;
}
string source = string.Concat(sourceNode.Nodes());
Console.WriteLine(source);
Try following :
string xml =
"<trans-unit id=\"7655230f\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\">" +
"<source>EC<x id=\"0040\" /><g id=\"0041\"> test</g></source> " +
"</trans-unit>";
XElement unit = XElement.Parse(xml);
XNamespace ns = unit.GetDefaultNamespace();
string ec = (string)unit.Element(ns + "source");
Related
How I can get all nodes from XSD in C# like this:
I have this example:
Data I need:
employees/
employees/employee/
employees/employee/name
employees/employee/adress
employees/employee/adress/postalcode/
I need all possible node from XSD. I used XmlSchema element.Attribute but I can get parent nodes, any ideas?
My Code:
var xs = XNamespace.Get("http://www.w3.org/2001/XMLSchema");
var doc = XDocument.Parse(xml);
string node = string.Empty;
foreach (var element in doc.Descendants(xs + "element"))
{
string name = element.Attribute("name").Value+"/";
node += name;
}
I'm new to using Linq and XMLDocument.
I have a simple XML file and I want to loop through all of the elements and print the tag and value. I don't want to use the XML Tags when looping through. this is what I have so far.
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<Step1>One
<Step2>Two
<Step3>Three
<Step4>Four
</Step4>
</Step3>
</Step2>
</Step1>
C# Code
private void StartIt()
{
System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
xd.Load(#"C:\Projects\GetXML\testLayers.xml");
XmlNodeList nl = xd.SelectNodes("Layer1");
foreach (XmlNode xnode in nl)
{
Console.WriteLine(xnode.Name + " = " + xnode.InnerText); // + " " + xnode.InnerXml);
}
}
Results:
Step1 = One
Two
Three
Four
What I want:
Step1 = One
Step2 = Two
Step3 = Three
Step4 = Four
Any suggestions?
With a little help of Linq,
XmlDocument doc = new XmlDocument();
doc.Load(fname);
var nodes = doc.SelectNodes("//*[text()]")
.Cast<XmlNode>()
.Select(n => new {
Name= n.Name,
Value = n.SelectSingleNode("text()").Value
})
.ToList();
// System.Xml.XmlDocument version
XmlDocument xd = new XmlDocument();
xd.Load(#"C:\Projects\GetXML\testLayers.xml");
foreach (XmlElement step in xd.SelectNodes("//*"))
{
Console.WriteLine("{0} = {1}", step.Name,
step.SelectSingleNode("text()").Value);
}
// System.Xml.Linq.XDocument version
XDocument xdLinq = XDocument.Load(#"C:\Projects\GetXML\testLayers.xml");
foreach (XElement step in xdLinq.XPathSelectElements("//*"))
{
Console.WriteLine("{0} = {1}", step.Name,
step.Nodes().Where(n => n.NodeType == XmlNodeType.Text).FirstOrDefault());
}
You can do the same using LINQ to XML and XDocument class:
var xDoc = XDocument.Load("Input.txt");
foreach (var e in xDoc.Descendants())
{
Console.WriteLine("{0} = {1}", e.Name, e.Nodes().OfType<XText>().First().Value.Trim());
}
My goal is to save the data contained in the ValueReference node, TimeInstant attribute, and timePosition node into variables. I am able to get the value of the valueReference node (the un-commented section works), but not the other two.
Any help would be greatly appreciated.
Here is the code that I am working on:
public void LinqToXml()
{
XNamespace sosNamespace = XNamespace.Get("http://www.opengis.net/sos/2.0");
XNamespace fesNamespace = XNamespace.Get("http://www.opengis.net/fes/2.0");
XNamespace gmlNamespace = XNamespace.Get("http://www.opengis.net/gml/2.0");
var root = XElement.Load(#"C:\Working Directory\OGCSOS.Service\OGCSOS.Service\Resources\GetObservation_TemporalFilter.xml");
var a = (from level in root.Descendants(sosNamespace + "temporalFilter")
select new
{
valueReference = (string)level.Descendants(fesNamespace + "After")
.Elements(fesNamespace + "ValueReference")
.First(),
/*timeInstant = (string)level.Descendants(fesNamespace + "After")
.Elements(gmlNamespace + "TimeInstant")
.Attributes(gmlNamespace + "id")
.First()*/
/*timePosition = (string)level.Descendants(fesNamespace + "After")
.Elements(gmlNamespace + "TimeInstant")
.First()*/
}).ToList();
And here is the XML I am trying to read:
<?xml version="1.0" encoding="UTF-8"?>
<sos:GetObservation xmlns="http://www.opengis.net/sos/2.0" service="SOS" version="2.0.0"
xmlns:sos="http://www.opengis.net/sos/2.0" xmlns:fes="http://www.opengis.net/fes/2.0"
xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:swe="http://www.opengis.net/swe/2.0"
xmlns:swes="http://www.opengis.net/swes/2.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/sos/2.0
http://schemas.opengis.net/sos/2.0/sos.xsd">
<!--identifier of an offering-->
<offering>HG.Logger#DJK001</offering>
<!--identifier of an observed property-->
<observedProperty>HG</observedProperty>
<!--optional temporal filter restricting the results which shall be returned-->
<temporalFilter>
<fes:After>
<fes:ValueReference>phenomenonTime</fes:ValueReference>
<gml:TimeInstant gml:id="startPosition">
<gml:timePosition>2008-03-01T17:44:15.000+00:00</gml:timePosition>
</gml:TimeInstant>
</fes:After>
</temporalFilter>
<featureOfInterest>DJK001</featureOfInterest>
</sos:GetObservation>
Your gml namespace is not correct, after changing it to
XNamespace gmlNamespace = XNamespace.Get("http://www.opengis.net/gml/3.2");
you can use
timeInstant = level.Descendants(fesNamespace + "After")
.First()
.Element(gmlNamespace + "TimeInstant")
.Attribute(gmlNamespace + "id")
.Value,
timePosition = level.Descendants(fesNamespace + "After")
.First()
.Element(gmlNamespace + "TimeInstant")
.Value
You should do it like this
XNamespace sosNamespace = "http://www.opengis.net/sos/2.0";
XNamespace fesNamespace = "http://www.opengis.net/fes/2.0";
XNamespace gmlNamespace = "http://www.opengis.net/gml/3.2";
//you had used 2.0 instead of 3.2
var root = XElement.Load(#"C:\WorkingDirectory\OGCSOS.Service\OGCSOS.Service\Resources\GetObservation_TemporalFilter.xml");
var yourList=root.Descendants(sosNamespace+"temporalFilter").Descendants(fesNamespace+"After").Select(x=>
new
{
ValueReference=x.Element(fesNamespace+"ValueReference").Value,
timeInstant=x.Element(gmlNamespace+"TimeInstant").Attribute(gmlNamespace+"id").Value,
timePosition=x.Element(gmlNamespace+"TimeInstant").Element(gmlNamespace+"timePosition").Value
}
);
yourList contains all the data
you can also use good old XPath
var doc = new XPathDocument("1.xml");
var nav = doc.CreateNavigator();
var mng = new XmlNamespaceManager(nav.NameTable);
mng.AddNamespace("sos", "http://www.opengis.net/sos/2.0");
mng.AddNamespace("fes", "http://www.opengis.net/fes/2.0");
mng.AddNamespace("gml", "http://www.opengis.net/gml/3.2");
var valueReference = nav.SelectSingleNode("//sos:GetObservation/sos:temporalFilter/fes:After/fes:ValueReference[1]", mng).TypedValue;
var TimeInstant = nav.SelectSingleNode("//sos:GetObservation/sos:temporalFilter/fes:After/gml:TimeInstant/#gml:id", mng).TypedValue;
var timePosition = nav.SelectSingleNode("//sos:GetObservation/sos:temporalFilter/fes:After/gml:TimeInstant/gml:timePosition[1]", mng).TypedValue;
TRY THIS CODE:
XmlDocument xmlSnippet = new XmlDocument();
xmlSnippet.Load(#"C:\Working Directory\OGCSOS.Service\OGCSOS.Service\Resources\GetObservation_TemporalFilter.xml");
//Selects all the similar nodes by tag Name.......
XmlNodeList xmlSnippetNodes = xmlSnippet.GetElementsByTagName("fes:After");
//Checking if any any xmlSnippetNode has matched.
if (xmlSnippetNodes != null)
{
//Checks if the matched xmlSnippetNode that has fes:After attribute is not NULL
//Stores the value of the matched tag.
var valueReference= xmlSnippetNodes.Item(0).Value;
var timeInstance=xmlSnippetNodes.Item(1).Attributes["gml:id"].Value;
var timePosition =xmlSnippetNodes.Item(1).InnerXml.Name;
//Return True if updated correctly.
isUpdated = true;
}
I want to get all text nodes from an XML file.
How can I do this?
Example Input:
<root>
<slide>
<Image>hi</Image>
<ImageContent>this</ImageContent>
<Thumbnail>is</Thumbnail>
<ThumbnailContent>A</ThumbnailContent>
</slide>
</root>
Expected Output:
hi this is A
The only solution (so far) to enumerate all text nodes in any xml, regardless of its structure:
string input = #"
<root>
<slide>
<Image>hi</Image>
<ImageContent>this</ImageContent>
<Thumbnail>is</Thumbnail>
<ThumbnailContent>A</ThumbnailContent>
</slide>
</root>";
foreach (XText text in (IEnumerable)XDocument.Parse(input).XPathEvaluate("//*/text()"))
{
Console.WriteLine(text.Value);
}
EDIT: if you want to load xml from file then use XDocument.Load instead.
This code will print the inner text of all xml nodes which doesnt have a child:
static void Main(string[] args)
{
XmlDocument x = new XmlDocument();
x.Load("exp.xml");
PrintNode(x.DocumentElement);
}
private static void PrintNode(XmlNode x)
{
if (!x.HasChildNodes)
Console.Write(string.Format("{0} ", x.InnerText));
for (int i = 0; i < x.ChildNodes.Count; i++)
{
PrintNode(x.ChildNodes[i]);
}
}
On your example XML it will result in the output you want :)
You can try this:
string input = #"
<root>
<slide>
<Image>hi</Image>
<ImageContent>this</ImageContent>
<Thumbnail>is</Thumbnail>
<ThumbnailContent>A</ThumbnailContent>
</slide>
</root>";
XDocument doc = XDocument.Parse(input);
//You can also load data from file by passing file path to Load method
//XDocument doc = XDocument.Load("Data.xml");
foreach(var slide in doc.Root.Elements("slide"))
{
var words = slide.Elements().Select(el => el.Value);
string s = String.Join(" ", words.ToArray());
}
This will work
static void Main(string[] args)
{
XDocument xmlSkuDescDoc = XDocument.Parse
(#"<root>
<slide>
<Image>hi</Image>
<ImageContent>this</ImageContent>
<Thumbnail>is</Thumbnail>
<ThumbnailContent>A</ThumbnailContent>
</slide>
</root> "
);
var result = (from data in xmlSkuDescDoc.Descendants("slide")
select data).Elements().Select(i => i.Value).Aggregate((a, b) => a + " " + b);
Console.ReadKey();
}
N.B.~ use XDocument.Load(filename) if loading from file
e.g.
string fileName = #"D:\MyXml.xml";
XDocument xmlSkuDescDoc = XDocument.Load(filename);
.... and the rest follows as shown above
It can be done using XDocument class (LINQ to XML). Assuming that you have exactly one slide element:
Using plain XDocument navigation:
var doc = XDocument.Load("file path here");
if (doc.Root == null)
throw new ArgumentException(); // No root node!
var slideElement = doc.Root.Element("slide");
if (slideElement == null)
throw new ArgumentException(); // No slide node!
var values = string.Join(" ", slideElement.Elements().Select(element => element.Value));
Using XPath node selection:
var doc = XDocument.Load("file path here");
var slideElements = doc.XPathSelectElements("root/slide/*");
var values = string.Join(" ", slideElements.Select(element => element.Value));
I am trying to get the plain text from the xaml content of the SL 4 rich text box.
The content looks like this:
<Section xml:space=\"preserve\" HasTrailingParagraphBreakOnPaste=\"False\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">
<Paragraph FontSize=\"12\" FontFamily=\"Arial\" Foreground=\"#FF000000\" FontWeight=\"Normal\" FontStyle=\"Normal\" FontStretch=\"Normal\" TextAlignment=\"Left\">
<Run Text=\"Biggy\" />
</Paragraph>
</Section>
When I try this:
XElement root = XElement.Parse(xml);
var Paras = root.Descendants("Paragraph");
foreach (XElement para in Paras)
{
foreach (XElement run in Paras.Descendants("Run"))
{
XAttribute a = run.Attribute("Text");
text += null != a ? (string) a : "";
}
}
Paras is empty.
What am I doing wrong?
Thanks for any hints...
You need to account for the namespace in your XML when selecting elements, you can use XNamespace to declare and use it - this works:
XNamespace xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
var Paras = root.Descendants(xmlns + "Paragraph");
Thanks to BrokenGlass.The full function:
string StringFromRichTextBox(string XAML)
{
XElement root = XElement.Parse(XAML);
XNamespace xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
StringBuilder sb = new StringBuilder();
var Paras = root.Descendants(xmlns + "Paragraph");
foreach (XElement para in Paras)
{
foreach (XElement run in Paras.Descendants(xmlns + "Run"))
{
XAttribute a = run.Attribute("Text");
sb.Append(null != a ? (string)a : "");
}
}
return sb.ToString();
}
It worked! Hope this help you.
Nguyen Minh Hien