Reading XML file using Linq - c#

I have tried to read XML file using Linq. Here is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqToXml
{
class Program
{
static void Main(string[] args)
{
XDocument xdoc = XDocument.Load(#"E:\\XML\\test.xml");
xdoc.Descendants("Title").Select(t => new
{
fontType = t.Attribute("fontType").Value,
fontSize = t.Attribute("fontSize").Value,
fontColor = t.Attribute("fontColor").Value,
Underline = t.Attribute("Underline").Value,
Bold = t.Attribute("Bold").Value,
Italic = t.Attribute("Italic").Value,
}).ToList().ForEach(t =>
{
Console.WriteLine("fontType : " + t.fontType);
Console.WriteLine("fontSize : " + t.fontSize);
Console.WriteLine("fontColor : " + t.fontColor);
Console.WriteLine("Underline : " + t.Underline);
Console.WriteLine("Bold : " + t.Bold);
Console.WriteLine("Italic : " + t.Italic);
});
Console.ReadLine();
}
}
}
It gives an below exception
An unhandled exception of type 'System.NullReferenceException'
occurred in programm.exe
But I can't find what is the error. Can anyone help me..
This is the XML file which I have used..
<Styles>
<Title>
<fontType>TimesNewRoman</fontType>
<fontSize>20</fontSize>
<fontColor>black</fontColor>
<Underline>No</Underline>
<Bold>bold</Bold>
<Italic>No</Italic>
</Title>
<Title>
<fontType>TimesNewRoman</fontType>
<fontSize>20</fontSize>
<fontColor>black</fontColor>
<Underline>No</Underline>
<Bold>bold</Bold>
<Italic>italic</Italic>
</Title>
</Styles>

There aren't any fontType, fontSize, etc. attributes on the Title element. fontType, fontSize are elements, so you should use
fontType = t.Element("fontType").Value

Related

How to replace Xml Attribute Prefix value by using C#

<ce_table frame="topbot" id="t0010" rowsep="0" colsep="0">
<ce_label>Table 2</ce_label>
<ce_caption id="cn040">
<ce_simple-para id="spar055">Model fit cnbs for the span targeted moments.</ce_simple-para>
</ce_caption>
</ce_label>
</ce_table>
I need to change id="t0010" to id="tf0010" and id="cn.. " to id="cib.. ".
I only need to change prefix of an attribute value.
Use xml linq :
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication2
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement ce_table = doc.Descendants("ce_table").First();
ce_table.SetAttributeValue("id", "tf0010");
XElement ce_caption = ce_table.Descendants("ce_caption").First();
ce_caption.SetAttributeValue("id", "cib040");
}
}
}

Update multiple XML nodes that match an Xpath query C#

I am trying to update the content of multiple nodes that match a specific xpath. For example, in the below example, I want to update any attribute1 node that currently is '2' with 'Hello'. What is the best way to do this?
(DotNetFiddle Here)
using System;
using System.IO;
using System.Xml;
using System.Linq;
public class Program
{
public static void Main()
{
XmlDocument job = new XmlDocument();
job.LoadXml(#"<parent>" +
"<report>" +
"<main>" +
"<attribute1>2</attribute1>"+
"<attribute1>2</attribute1>"+
"<attribute1>3</attribute1>"+
"</main>"+
"</report>" +
"</parent>");
string newAttribute1Value = "Hello";
//How do I update both attribute1's where value=2?
}
This may could help you :
using System;
using System.IO;
using System.Xml;
using System.Linq;
public class Program
{
public static void Main()
{
XmlDocument job = new XmlDocument();
job.LoadXml(#"<parent>" +
"<report>" +
"<main>" +
"<attribute1>2</attribute1>"+
"<attribute1>2</attribute1>"+
"<attribute1>3</attribute1>"+
"</main>"+
"</report>" +
"</parent>");
string newAttribute1Value = "Hello";
//How do I update both attribute1's where value=2?
// getting the list of nodes with XPath query :
XmlNodeList nodes = job.SelectNodes("//attribute1[text()=2]");
foreach (XmlNode child in nodes)
{
// replacing the old value with the new value
child.InnerText = newAttribute1Value ;
}
}

Parsing a Complex XML file with in C#

- <SynchroAnimation Duration="10" EndTime="10000" ModelFileName="Lukes box (named).fbx" StartTime="0" SynchroVersion="5.2.2.0" Version="2">
- <Resource Identifier="AA67882D-9AC1-4450-90D1-2C1C7FF8F6BC" Name="Box Side - Growth" NumAnimatedInstances="1">
- <Resource3DRepresentation>
- <Entity3D Identifier="7D972BE6-9B4A-4A86-93C5-4256FB1DCE8F" Name="Basic Wall Wall-Ext_102Bwk-75Ins-100LBlk-12P [294917]">
+ <PreTransform>
<M0>0.003280840348452</M0>
</PreTransform>
+ <PostTransform>
<M0>304.799987792968750</M0>
</PostTransform>
</Entity3D>
</Resource3DRepresentation>
- <ResourceInstance>
- <VisibilityTimeline>
- <VisibilityKeyframe Interpolation="Discrete" Time="0" UseOriginal="false">
<VisibilityValue>0</VisibilityValue>
</VisibilityKeyframe>
- <VisibilityKeyframe Interpolation="Discrete" Time="1822" UseOriginal="false">
<VisibilityValue>100</VisibilityValue>
</VisibilityKeyframe>
</VisibilityTimeline>
- <ColorTimeline>
+ <ColorKeyframe Time="1822" UseOriginal="false">
+ <ColorValue>
<R>0.00</R>
<G>0.00</G>
<B>1.00</B>
</ColorValue>
</ColorKeyframe>
<ColorKeyframe Time="8066" UseOriginal="true" />
</ColorTimeline>
+ <TransformTimeline>
<TransformKeyframe Interpolation="Discrete" Time="1822" UseOriginal="true" />
</TransformTimeline>
</ResourceInstance>
</Resource>
+ <Resource Identifier="11F593C9-5A33-4E24-A41F-7F003404E346" Name="Box Side - Fade In" NumAnimatedInstances="1">
- <Resource3DRepresentation>
+ <Entity3D Identifier="88D87801-2C5D-4F20-BBB9-21566D230A33" Name="Basic Wall
MORE Resco
</SynchroAnimation>
snExported FBX XML
I'm trying to get the highlighted values from the attached image XML file. I need to get the values in "3D id" so it can be attached to the correct game object inside unity game engine with the correct metadata (i.e.: start time and date).
This is the code I currently have, but this is my first time dealing with XML files so any help would be appreciated.
using UnityEngine;
using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;
public class XML : MonoBehaviour
{
public string filepath = "filepath";
public string filename = "filename";
public string filetype = ".xml";
void start()
{
XDocument xDoc = XDocument.Load(filepath + filename + filetype);
var resourceinfo = from rescourse in xDoc.Descendants("Resource")
where rescourse.Attribute("Name").Value == "Growth"
select new
{
Resource = rescourse.Descendants("Resource").Descendants(),
ResourceInstance = rescourse.Descendants("Resource3DRepresentation").Descendants(),
};
foreach (var rescourse in resourceinfo)
{
string name = rescourse.Resource.ElementAt(1).Attribute("Name").Value;
Debug.Log(name);
}
}

Create Protege Readable Ontology from .NET

I am trying to create a protégé readable ontology from .NET.
I started with a 4GB .nt file and parsed out the needed classes and instances that I wish to use. Those are stored in memory since I got it down to less than 1 minute and roughly 1GB. They are in the form of Dictionary<String,HashSet<String>> right now. The next step is to take that data and move it into an OWL Ontology. Is there anywhere to start with how to manually loop through and do this? All of my research points me to using Manchester OWL, but everything I can find is for use with existing tools that don't fit my needs. I am looking for just doing a simple loop probably with LINQ to XML and I am unsure of how to format that or where to look to find how to do this.
Thanks
Jimmy
You can start with this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string definition =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<Ontology xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xsi:schemaLocation=\"http://www.w3.org/2002/07/owl# http://www.w3.org/2009/09/owl2-xml.xsd\"" +
" xmlns=\"http://www.w3.org/2002/07/owl#\"" +
" xml:base=\"http://example.com/myOntology\"" +
" ontologyIRI=\"http://example.com/myOntology\">" +
"</Ontology>";
XDocument doc = XDocument.Parse(definition);
XElement ontology = (XElement)doc.FirstNode;
XNamespace ns = ontology.Name.Namespace;
ontology.Add(new XElement[] {
new XElement(ns + "Prefix", new XAttribute[] {
new XAttribute("name", "myOnt"),
new XAttribute("IRI", "http://example.com/myOntology#")
}),
new XElement(ns + "Import", "http://example.com/someOtherOntology")
});
}
}
}
​

Unable to Parse XMl after unwrapping soap body

I have been trying hard to parse an xml string, but all to no avail
<EnquirySingleItemResponse xmlns="http://tempuri.org/"> <EnquirySingleItemResult>
<Response>
<MSG>SUCCESS</MSG>
<INFO>TESTING</INFO>
</Response> </EnquirySingleItemResult> </EnquirySingleItemResponse>
My Code returns null or the texts in the xml tags no matter how i parse it. I have checked some post, but they seem not to be working.
See my code snipped below
XElement anotherUnwrappedResponse = ( from _xml in axdoc.Descendants(tempuri + "EnquirySingleItemResponse")
select _xml).FirstOrDefault();
string response = anotherUnwrappedResponse.Value;
axdoc.Descendants is used because i unwrapped the soap body, to have the xml above
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input =
"<EnquirySingleItemResponse xmlns=\"http://tempuri.org/\">" +
"<EnquirySingleItemResult>" +
"<Response>" +
"<MSG>SUCCESS</MSG>" +
"<INFO>TESTING</INFO>" +
"</Response> </EnquirySingleItemResult> </EnquirySingleItemResponse>";
XDocument doc = XDocument.Parse(input);
string msg = doc.Descendants().Where(x => x.Name.LocalName == "MSG").FirstOrDefault().Value;
string info = doc.Descendants().Where(x => x.Name.LocalName == "INFO").FirstOrDefault().Value;
}
}
}
​

Categories