I'm new to C#. I created a class in a separate file for processing text. Both the main and text processing class are in the TextProcessing namespace. This is not the whole class, just the beginning:
using System;
using System.Linq;
using System.Xml.Linq;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
namespace TextProcessing
{
public class Para2XML
{
private Paragraph XMLP;
public Para2XML(string PText)
{
var xmlParagraph = XElement.Parse(PText);
var XMLP = (Paragraph)TransformElementToOpenXml(xmlParagraph);
}
public Paragraph PReturn
{
get { return XMLP; }
}
private static OpenXmlElement TransformElementToOpenXml(XElement element)
{
return element.Name.LocalName switch
{
"p" => new Paragraph(element.Nodes().Select(TransformNodeToOpenXml)),
"em" => new Run(new RunProperties(new Italic()), CreateText(element.Value)),
"b" => new Run(new RunProperties(new Bold()), CreateText(element.Value)),
_ => throw new ArgumentOutOfRangeException()
};
}
Back in my program, this is where I instantiate the class:
foreach (var bkmkStart in wordDoc.MainDocumentPart.RootElement.Descendants<BookmarkStart>())
{
if (bkmkStart.Name == "ForewordText")
{
forewordbkmkParent = bkmkStart.Parent;
for (var y = 0; y <= ForewordArray.Length - 1; y++)
{
Para2XML TextProcessP = new Para2XML(ForewordArray[y]);
forewordbkmkParent.InsertBeforeSelf(PReturn);
}
}
}
PReturn is public in the Para2XML class, but it acts like it's out of scope in the main class. In the main class, a red underline appears under PReturn with the message "The name 'PReturn' does not exist in the current context". If I declare PReturn in the main class, I get "Do not declare visible instance fields." I'm baffled how to return the XElement to the program from a class in a separate file.
I hope someone can point out my error. Thanks!